如何确保在关闭 fstream 之前将数据写入磁盘?
下面的内容看起来很合理,但我听说即使在 close() 调用之后,数据理论上仍然可以位于缓冲区中而不是磁盘上。
#include <fstream>
int main()
{
ofstream fsi("test.txt");
fsi << "Hello World";
fsi.flush();
fsi.close();
return 0;
}
The following looks sensible, but I've heard that the data could theoretically still be in a buffer rather than on the disk, even after the close() call.
#include <fstream>
int main()
{
ofstream fsi("test.txt");
fsi << "Hello World";
fsi.flush();
fsi.close();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您无法使用标准工具来实现此目的,并且必须依赖操作系统设施。
对于 POSIX
fsync
应该是您所需要的。由于无法从标准流中获取 C 文件描述符,因此您必须在整个应用程序中求助于 C 流,或者只是打开文件以刷新磁盘。或者,还有sync
,但这会刷新所有缓冲区,这是您的用户和其他应用程序会讨厌的。You cannot to this with standard tools and have to rely on OS facilities.
For POSIX
fsync
should be what you need. As there is no way to a get C file descriptor from a standard stream you would have to resort to C streams in your whole application or just open the file for flushing do disk. Alternatively there issync
but this flushes all buffers, which your users and other applications are going to hate.您可以通过刷新流来保证缓冲区中的数据写入磁盘。这可以通过调用其
flush()
成员函数、flush
操纵器、endl
操纵器来完成。但是,在您的情况下不需要这样做,因为
close
保证将任何挂起的输出序列写入物理文件。You could guarantee the data from the buffer is written to disk by flushing the stream. That could be done by calling its
flush()
member function, theflush
manipulator, theendl
manipulator.However, there is no need to do so in your case since
close
guarantees that any pending output sequence is written to the physical file.您使用哪个操作系统?
您需要使用直接(非缓冲)I/O 来保证数据直接写入物理设备,而不会触及文件系统写入缓存。请注意,在进行物理写入之前,它仍然必须通过磁盘缓存。
在 Windows 上,打开文件时可以使用 FILE_FLAG_WRITE_THROUGH 标志。
Which operating system are you using?
You need to use Direct (non-buffered) I/O to guarantee the data is written directly to the physical device without hitting the filesystem write-cache. Be aware it still has to pass thru the disk cache before getting physically written.
On Windows, you can use the FILE_FLAG_WRITE_THROUGH flag when opening the file.
它保证刷新文件。但是,请注意,操作系统可能会对其进行缓存,并且操作系统可能不会立即刷新它。
It's guaranteed to flush the file. However, note that the OS might keep it cached, and the OS might not flush it immmediately.
我很确定调用 close() 的全部目的是刷新缓冲区。 本网站同意。尽管取决于您的文件系统和挂载设置,但仅仅因为您已“写入磁盘”并不意味着您的文件系统驱动程序和磁盘硬件实际上已获取数据并在物理金属上制作了磁性位。它可能仍然在磁盘缓冲区中。
I'm pretty sure the whole point of calling
close()
is to flush the buffer. This site agrees. Although depending on your file system and mount settings, just because you've 'written to the disk' doesn't mean that your file system drivers and disk hardware have actually taken the data and made magnet-y bits on the physical piece of metal. It could probably be in a disk buffer still.close()
成员函数关闭底层操作系统文件描述符。此时,该文件应该位于磁盘上。The
close()
member function closes the underlying OS file descriptor. At that point, the file should be on disk.关闭前如何刷新?
How abt flushing before closing?