对于下面的代码片段,当std::fstream被销毁时,文件是否保证在\之后写入磁盘?
//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;
}
保证首先调用代码段。
由于操作系统可能会推迟实际操作(这是C++无法控制的),现在可能在磁盘上没有实际文件。我不确定是否存在潜在的问题,如果我调用下面的代码片段来读取由第一个代码片段在销毁后创建和编写的文件,那么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;
}
发布于 2022-08-24 23:52:03
您可以使用输出流创建文件,该文件通常是同步的。
然后,将输出流写到文件,这通常是通过页面缓存进行的。
因此,在运行第一个程序之后,该文件就可以读取数据和存在性了。
问题更深一点,因为您假设程序的运行顺序,在100%的情况下,这要求您在外部同步(通过PID文件或信号量)。
https://stackoverflow.com/questions/73483711
复制相似问题