Will fseek function flush data in the buffer in C++?

喜你入骨 提交于 2019-12-02 04:23:43

问题


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


回答1:


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.




回答2:


Yes; fseek() ensures that the file will look like it should according to the fwrite() operations you've performed.

The C standard, ISO/IEC 9899:1999 §7.19.9.2 fseek(), says:

The fseek function sets the file position indicator for the stream pointed to by stream. If a read or write error occurs, the error indicator for the stream is set and fseek fails.




回答3:


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.




回答4:


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.




回答5:


I have vague memories of a requirement that you call fflush before fseek, 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:

If the most recent operation, other than ftell(), on a given stream is fflush(), the file offset in the underlying open file description shall be adjusted to reflect the location specified by fseek().

[...]

If the stream is writable and buffered data had not been written to the underlying file, fseek() shall cause the unwritten data to be written to the file and shall mark the st_ctime and st_mtime fields of the file for update.

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).



来源:https://stackoverflow.com/questions/7495891/will-fseek-function-flush-data-in-the-buffer-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!