For the code snippet below, does the file is guaranteed to be written to the disk just after\when the std::fstream is destroyed?
//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;
}
The code snippet is guaranteed to be called first.
Since the OS may defer the actual operation, which is out of the control of C++, there may be no actual file on the disk right now. I am not sure whether there is any potential problem or not if I call the code snippet below to read the file which is created and written by the first code snippet right after the file_writer
has been destroyed.
//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;
}