We know that call to functions like fprintf or fwrite will not write data to the disk immediately, instead, the data will be buffered until a threshold is reached. My question is, if I call the fseek function, will these buffered data writen to disk before seeking to the new position? Or the data is still in the buffer, and is writen to the new position?
cheng
It seems that your real concern is whether previously-written (but not yet flushed) data would end up in the wrong place in the file if you do an
fseek
.No, that won't happen. It'll behave as you'd expect.
I have vague memories of a requirement that you call
fflush
beforefseek
, but I don't have my copy of the C standard available to verify. (If you don't it would be undefined behavior or implementation defined, or something like that.) The common Unix standard specifies that:This is marked as an extention to the ISO C standard, however, so you can't count on it except on Unix platforms (or other platforms which make similar guarantees).
I don't believe that it's specified that the data must be flushed on a
fseek
but when the data is actually written to disk it must be written at that position that the stream was at when the write function was called. Even if the data is still buffered, that buffer can't be written to a different part of the file when it is flushed even if there has been a subsequent seek.I'm not aware if the buffer is guaranteed to be flushed, it may not if you seek to a position close enough. However there is no way that the buffered data will be written to the new position. The buffering is just an optimization, and as such it has to be transparent.
Yes;
fseek()
ensures that the file will look like it should according to thefwrite()
operations you've performed.The C standard, ISO/IEC 9899:1999 §7.19.9.2
fseek()
, says: