Reputation: 2904
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.
Upvotes: 4
Views: 4755
Reputation: 399863
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.
Upvotes: 0
Reputation: 328614
This only works when the new line has the same size as the old one:
a+
fseek()
to the start of the fileftell()
to note the start of the linefseek()
again with the result from ftell()
and use fwrite()
to overwrite it.If the length of the line changes, you must copy the file.
Upvotes: 8