Q: I’m trying to update a file in
place, by usingfopenmode"r+",
reading a certain string, and writing
back a modified string, but it’s not
working.A: Be sure to call
fseekbefore
you write, both to seek back to the
beginning of the string you’re trying
to overwrite, and because anfseek
orfflushis always required between
reading and writing in the read/write
“+” modes.
My question is why fseek or fflush is always required between reading and writing in the read/write “+” modes? Section 5.2 of
Andrew Koenig’s
C Traps and Pitfalls (1989) mentioned that it is because of a backward compatibility issue. Can anyone explain in detail?
The library buffers input and output operations. Check out
setvbuf()and the_IOFBF,_IOLBFparameters to that function.fseek()orfflush()require the library to commit buffered operations.The standard specifies a seek or flush operation (flushing the buffers) as mandatory prior to changing I/O direction to allow the library some shortcuts. Without this restriction, the library would have to check for every I/O operation if the previous operation was the same direction (reading / writing), and trigger a flush by itself if the I/O direction changed. With the restriction as-is, the library may assume the client did the seek / flush before changing I/O direction, and can omit the direction checks.