c++ std::ofstreamlush() 但不是 close()
我在 MacOSX 上。
在我的应用程序的记录器部分,我将数据转储到文件中。
假设我有一个全局声明的 std::ofstream outFile("log"); ,
并且在我的日志记录代码中我有:
outFile << "......." ;
outFile.flush();
现在,假设我的代码在flush()发生后崩溃了;在 flush()
之前写入 outFile
的内容是否保证写入磁盘(请注意,我没有调用 close()
)。
谢谢!
I'm on MacOSX.
In the logger part of my application, I'm dumping data to a file.
suppose I have a globally declared std::ofstream outFile("log");
and in my logging code I have:
outFile << "......." ;
outFile.flush();
Now, suppose my code crashes after the flush() happens; Is the stuff written to outFile
before the flush()
guaranteed to be written to disk (note that I don't call a close()
).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 C++ 运行时的角度来看,它应该已写入磁盘。从操作系统的角度来看,它可能仍然停留在缓冲区中,但只有当整个机器崩溃时,这才会成为问题。
From the C++ runtime's point of view, it should have been written to disk. From an OS perspective it might still linger in a buffer, but that's only going to be an issue if your whole machine crashes.
作为一种替代方法,您可以完全禁用缓冲,
写入无缓冲的 fstream 可能会损害性能,但在测量之前担心这一点将是过早的优化。
As an alternative approach, you can disable buffering altogether with
Writing to an unbuffered
fstream
may hurt performance, but worrying about that before measuring would be premature optimization.lush() 刷新 iostream 库的缓冲区 - 然而数据几乎肯定不会立即从操作系统的缓冲区中完全同时刷新,因此在一小段时间内操作系统崩溃可能会丢失数据。当然,如果你的硬盘出现故障,无论数据是否被写入,你都可能随时丢失数据,所以我不会太担心这一点。
flush() flushes the iostream library's buffers - however the data is almost certainly not immediately flushed from the operating system's buffers at exactly the same time, so there is a small period during in which an operating system crash could lose you data. You can of course lose data at any time if you suffer a hard disk failure, whether the data was written or not, so I wouldn't worry too much about this.
只要flush()返回,你的程序就成功地将输出交到操作系统手中。除非操作系统(或磁盘)崩溃,否则下次磁盘写入时您的数据应该在磁盘上(请注意,磁盘可能有自己的固态缓存)。
在flush()返回之前,谁都无法猜测有多少数据会被写入磁盘。
As long as flush() has returned, your program has successfully put the output in the OS's hands. Unless the OS (or disk) crashes, your data should be on disk next time the disk writes (note that the disk likely has a solid state cache of its own).
Until flush() returns, it's anybody's guess how much will make it to the disk.