如何确保在关闭fstream之前将数据写入磁盘? [英] How do I ensure data is written to disk before closing fstream?

查看:163
本文介绍了如何确保在关闭fstream之前将数据写入磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容看起来很明智,但我听说即使在close()调用之后,理论上数据也可能仍在缓冲区中,而不是在磁盘上.

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;
}

推荐答案

您不能使用标准工具来做到这一点,而必须依靠OS设施. 对于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 is sync but this flushes all buffers, which your users and other applications are going to hate.

这篇关于如何确保在关闭fstream之前将数据写入磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆