C++ 中的 fseek 函数会刷新缓冲区中的数据吗?
我们知道调用 fprintf 或 fwrite 等函数不会立即将数据写入磁盘;相反,数据将被缓冲,直到达到阈值。我的问题是:如果我调用 fseek 函数,这些缓冲数据会在查找新位置之前写入磁盘吗?或者数据仍在缓冲区中,并写入新位置?
We know that calls 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 be written to disk before seeking to the new position? Or is the data still in the buffer, and is written to the new position?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不知道缓冲区是否保证被刷新,如果您寻求足够接近的位置,则可能不会。但是,缓冲数据无法写入新位置。缓冲只是一种优化,因此它必须是透明的。
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.
是的;
fseek()
确保文件看起来与您执行的fwrite()
操作一致。C 标准,ISO/IEC 9899:1999 §7.19.9.2
fseek()
(C11 §7.21.9.2fseek
函数,说: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()
(C11 §7.21.9.2 Thefseek
function, says:我不认为指定数据必须在 fseek 上刷新,但是当数据实际写入磁盘时,必须将其写入写入函数时流所在的位置叫。即使数据仍在缓冲中,该缓冲区在刷新时也无法写入文件的其他部分,即使已经进行了后续查找。
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.看来您真正关心的是,如果您执行
fseek
,先前写入(但尚未刷新)的数据是否会最终出现在文件中的错误位置。不,那不会发生。它会按照您的预期运行。
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.
我模糊记得你之前调用过 fflush 的一个要求
fseek
,但我没有可供验证的 C 标准副本。(如果不这样做,这将是未定义的行为或定义的实现,
或类似的东西。)通用 Unix 标准指定:
然而,这被标记为 ISO C 标准的扩展,因此除了 Unix 平台(或做出类似保证的其他平台)之外,您不能指望它。
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).