Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::ofstream flush() but not close()

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!

like image 579
anon Avatar asked Feb 26 '10 11:02

anon


People also ask

Do you have to close Ofstream C++?

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.

Do you have to close Ofstream?

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.

Does close flush C++?

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.

What is std :: flush in C++?

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.


1 Answers

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.

like image 122
Timo Geusch Avatar answered Oct 13 '22 13:10

Timo Geusch