Reputation: 6779
I want to append a file and update some of its lines at the same time. After appending as I desired, say I want to change only the first line, here is what I tried:
outputptr = fopen(outputName.c_str(), "ar+b");
cout << ftell(outputptr) << " ";
rewind(outputptr);
cout << ftell(outputptr) << "\n";
fprintf(outputptr, "abc");
But that code do not replace the first three letters with abc, instead it also appends the file and writes abc to the end. cout
were 60 and 0 for this case, so pointer in fact is moved to the beginning.
How do I go any line of a given file and modify only that line?
Upvotes: 0
Views: 1160
Reputation: 129344
The definition of 'a'
in the mode field says:
(I've cut out the bits that are relevent for this question - it says some other stuff too)
... Repositioning operations (
fseek
,fsetpos
,rewind
) affects the next input operations, but output operations move the position back to the end of file. ...
You probably want "r+b"
.
http://www.cplusplus.com/reference/cstdio/fopen/
Upvotes: 4