Why is fseek or fflush always required between reading and writing in the update modes?
The library buffers input and output operations. Check out setvbuf()
and the _IOFBF
, _IOLBF
parameters to that funktion.
fseek()
or fflush()
require the library to commit buffered operations.
The standard specifies a seek or flush operation as mandatory to allow the library some shortcuts; otherwise, for every I/O operation, the lib would have to check if the previous operation was also a read op (or a write op), and trigger a flush by itself if the "direction" of the I/O changed. With the specifications as-is, the library may assume the client did the seek / flush before changing I/O direction.
Because it keeps OS/library code simpler. A file stream may have separate read and write buffers, and extra effort would be required to make sure they are always synchronised. This would cost performance at times when it wasn't needed.
So instead, the programmer needs to do this explicitly when it is needed.
Note that the standard mandates this. This is from the C11 standard, ISO/IEC 9899:2011, but the wording was similar in prior editions:
§7.21.5.3 The
fopen
function¶7 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the
fflush
function or to a file positioning function (fseek
,fsetpos
, orrewind
), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.