Hello again,how do I go about overwriting a specific line on a text file in c?. I have values in multiple variables that need to be written onto the file.
+4
A:
This only works when the new line has the same size as the old one:
- Open the file in the mode
a+
fseek()
to the start of the file- Before reading the next line, use
ftell()
to note the start of the line - Read the line
- If it's the line you want,
fseek()
again with the result fromftell()
and usefwrite()
to overwrite it.
If the length of the line changes, you must copy the file.
Aaron Digulla
2009-12-02 13:03:24
Hi there, I'm new to this so dont know how to use fseek or ftell, do you know of any tutorials on its use?. -thanks.
sil3nt
2009-12-03 04:42:42
Sure: http://www.exforsys.com/tutorials/c-language/file-management-in-c.html
Aaron Digulla
2009-12-03 08:34:41
A:
Since files (from the point of view of C's standard library) are not line-oriented, but are just a sequence of characters (or bytes in binary mode), you can't expect to edit them at the line-level easily.
As Aaron described, you can of course replace the characters that make up the line if your replacement is the exact same character count.
You can also (perhaps) insert a shorter replacement by padding with whitespace at the end (before the line terminator). That's of course a bit crude.
unwind
2009-12-02 13:23:47