Skip to content
Advertisement

Editing single value in file in C efficiently

I have a C program that currently edits a single value in a parameter file by using sed through a system call. I’d like to change the program to use the C file libraries to edit this value, but the only way I know how to do this is by reading in the entire file, changing the value, and rewriting the file. Is there a more efficient way to do this? The program is intended for use on an embedded device so I’d like to use the most efficient solution possible.

Advertisement

Answer

Working with files is like working with arrays in the sense that one can’t truly before insertions and deletions. Insertions and deletions require shifting (copying) the rest of the file/array. Only replacing elements is possible (by opening the file for reading and writing, and using seek).

Reading and writing the entire file is quite efficient, especially for tiny files. If the memory usage isn’t an issue, that’s the approach I would take.

Other solutions might be better in specific circumstances, but the approach you describe is generally the best.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement