Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a file guaranteed to be openable for reading immidiately after ofstream::close() has returned?

I need my code (C++, on linux) to call a second executable, having previously written an output file which is read by the second program. Does the naïve approach,

std::ofstream out("myfile.txt");
// write output here
out.close();
system("secondprogram myfile.txt");

suffer from a potential race condition, where even though out.close() has executed, the file cannot immediately be read by secondprogram? If so, what is the best practice for resolving this?

Three notes:

  • If this is file-system-dependent, I'm interested in the behaviour on ext3 and tmpfs.
  • Clearly there are other reasons (file permissions etc.) why the second program might fail to open the file; I'm just interested in the potential for a race condition.
  • The hardcoded filename in the example above is for simplicity; in reality I use mkstemp.
like image 704
Chris Johnson Avatar asked Mar 26 '13 14:03

Chris Johnson


People also ask

Does ofstream destructor close file?

ofstream will close files when its destructor is called, i.e. when it goes out of scope.

What does ofstream do in c++?

Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.


1 Answers

Once the file has been closed, all the written data is guaranteed to be flushed from the buffers of the ofstream object (because at that point you can destroy it without any risk of losing whatsoever data, and actually closing the file is internally done by the destructor if needed). This does not mean that the data will at this point be physically on the disk (it will probably not, because of caching behavior of the OS disk drivers), but any program running in the same OS will be able to read the file consistently (as the OS will then perform the reading from the cached data). If you need to flush the OS buffers to the disk (which is not needed for your secondprogram to correctly read the input file), then you might want to look at the sync() function in <unistd.h>.

like image 69
Ale Avatar answered Sep 20 '22 14:09

Ale