c++ std::ofstreamlush() 但不是 close()

发布于 2024-08-23 05:45:16 字数 340 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

追风人 2024-08-30 05:45:16

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

深者入戏 2024-08-30 05:45:16

作为一种替代方法,您可以完全禁用缓冲,

outFile.rdbuf()->pubsetbuf(0, 0);

写入无缓冲的 fstream 可能会损害性能,但在测量之前担心这一点将是过早的优化。

As an alternative approach, you can disable buffering altogether with

outFile.rdbuf()->pubsetbuf(0, 0);

Writing to an unbuffered fstream may hurt performance, but worrying about that before measuring would be premature optimization.

奶茶白久 2024-08-30 05:45:16

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.

此岸叶落 2024-08-30 05:45:16

只要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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文