Reputation: 3494
For the code snippet below, does the file is guaranteed to be written to the disk just after\when the std::fstream is destroyed?
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
{
std::fstream file{"test.txt"};
file << "when the file is actually written out?" << std::endl;
}
return 0;
}
Upvotes: 2
Views: 303
Reputation: 904
Rephrasing my comment as an actual answer:
No. That code snippet does not guarantee the data to be on "persistent storage". You tell the os to take that file and store it. But the OS takes that data and gives it to the IO-scheduler. What the scheduler does or does not do is (paratially) out of your control, as that schedules the tasks as it sees fit.
You can however force the scheduler to write all pending metadata and data to "persistent storage" (read: the actual filesystem) by calling sync()
https://man7.org/linux/man-pages/man2/sync.2.html
Warning, assumption: What may be a problem with that is that you are ruling over the scheduler. So if for example another program on that machine has a huge file to write and the schedular wants to wait with that file write because of generally high io right now. If you call sync() you force the scheduler to write all (meta)data, so it will also write that file. Sync will not return untill all data is written. It does not matter where your write is in the queue, so it actually may take several seconds (minutes even on slow io and hughe files) for that call to return.
Idk how one would do that on windows or how windows actually handles disk writes at all
Upvotes: 3