std::ofstream销毁后文件是否确保写入磁盘?读取该文件存潜在问题吗?
关于C++文件流写入与读取的两个问题
写入代码(先执行)
//the writer #include<iostream> #include<fstream> #include<chrono> #include<thread> using namespace std; int main(int argc,char* argv[]){ { std::ofstream file_writer{"test.txt"}; file_writer << "when the file is actually written out?" << std::endl; } std::this_thread::sleep_for(std::chrono::seconds(3600)); //the reader below would be called and this process is still alive. return 0; }
当上述代码中的std::ofstream对象file_writer销毁后,立即执行以下读取代码:
读取代码
//the reader #include<iostream> #include<fstream> using namespace std; int main(int argc,char* argv[]){ { std::ifstream file_reader{"test.txt"}; file_reader.read(); } return 0; }
问题1:是否能保证std::fstream销毁时/后文件已写入磁盘?
不能。C标准仅保证std::ofstream销毁时,会把程序用户空间的缓冲区数据刷新到操作系统的文件缓存中,但完全不强制操作系统立刻将缓存数据写入物理磁盘。数据此时已经脱离了C程序的控制,但实际落盘时机由操作系统的磁盘调度策略决定,可能延迟数秒甚至更久。
问题2:由于操作系统可能延迟实际写入(不受C++控制),此时磁盘上可能无实际文件,这种场景下读取该文件是否存在潜在问题?
常规场景下读取不会有问题,但存在极端异常场景的风险:
- 多数现代操作系统会提供一致性保证:当一个进程关闭文件(
ofstream销毁会触发文件关闭)后,其他进程打开该文件时,能通过操作系统的缓存读到完整数据,哪怕数据还没刷到磁盘。 - 极端情况(比如操作系统突然崩溃、主机断电)下,如果数据还在系统缓存未写入磁盘,此时读取可能失败,或者读到旧的文件内容,但这属于系统级异常,不是日常运行会遇到的情况。
- 另外需要注意:你的读取代码中
file_reader.read()是语法错误,该函数需要传入缓冲区和读取长度参数(比如char buf[1024]; file_reader.read(buf, sizeof(buf));),否则无法通过编译,这是代码本身的问题,和磁盘写入延迟无关。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

