fstream::flush() 或 fstream::sync() 是否保证数据已写入磁盘?

梁宇坤*_*梁宇坤 5 c++ buffer fstream disk ofstream

我正在使用 C++ 编写一个迷你数据库。在日志模块中,我用于fstream将数据附加到日志文件中,并且需要将数据立即写入磁盘。在http://www.cplusplus.com/doc/tutorial/files/中,我发现

当缓冲区被刷新时,其中包含的所有数据都将写入物理介质。

但在http://www.cplusplus.com/forum/general/7343/

我尝试过flush()调用,但这只是将程序的缓冲区刷新到文件系统的缓冲区中,并不能保证数据物理写入磁盘。

例如,我很困惑flush()或sync()调用是否保证数据已写入磁盘

std::fstream file;
file.open("...", std::ios::out | std::ios::app); // open a file
file << "..."; //append log
file.flush(); //or file.sync()
//file.flush() has returned
//system crashed(not only program crashed) or an interruption in the supply of electricity heppened 
Run Code Online (Sandbox Code Playgroud)

那么当我重新启动计算机时,日志是否会丢失?如果日志丢失,有fstream什么办法可以强制将数据写入磁盘吗?