I'm on MacOSX.
In the logger part of my application, I'm dumping data to a file.
suppose I have a globally declared std::ofstream outFile("log");
and in my logging code I have:
outFile << "......." ;
outFile.flush();
Now, suppose my code crashes after the flush() happens; Is the stuff written to outFile
before the flush()
guaranteed to be written to disk (note that I don't call a close()
).
Thanks!
It is necessary to call close if you want to check the result (success or failure). Otherwise, the stream's destructor will attempt to close the file for you.
When the fstream/ifstream/ofstream object is out of scope, the file will be closed automatically. However, you can explicitly call the close() function to close it and release the resource if the fstream object will not be out of scope for a while.
NOTE: close() is typically called through the destructor of std::basic_filebuf (which, in turn, is typically called by the destructor of std::basic_fstream . First of all, we can see that it doesn't actually call flush() directly as you expected.
std::flushFlushes the output sequence os as if by calling os. flush(). This is an output-only I/O manipulator, it may be called with an expression such as out << std::flush for any out of type std::basic_ostream.
From the C++ runtime's point of view, it should have been written to disk. From an OS perspective it might still linger in a buffer, but that's only going to be an issue if your whole machine crashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With