Overwriting a specific line in a text file?

How do I rewrite a specific line in a text file in c ?. I have values ​​in several variables that need to be written to a file.

+2
c variables file file-writing writing
Dec 02 '09 at 13:00
source share
2 answers

This only works when the new line is the same size as the old one:

  • Open the file in a+ mode
  • fseek() to the beginning of the file
  • Before reading the next line, use ftell() to mark the beginning of a line
  • Read the line
  • If this is the desired line, fseek() again with the result of ftell() and use fwrite() to overwrite it.

If the line length changes, you must copy the file.

+6
Dec 02 '09 at 13:03
source share

Since the files (from the point of view of the standard C library) are not line oriented, but are simply a sequence of characters (or bytes in binary mode), you cannot expect to edit them on a linear level easily.

As Aaron described, you can, of course, replace the characters that make up the line if your replacement is exactly the same number of characters.

You can also (possibly) insert a shorter replacement by filling in spaces at the end (before the line terminator). This, of course, is a little rude.

0
Dec 02 '09 at 13:23
source share



All Articles