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

2019-02-06 05:53发布

问题:

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!

回答1:

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.



回答2:

As an alternative approach, you can disable buffering altogether with

outFile.rdbuf()->pubsetbuf(0, 0);

Writing to an unbuffered fstream may hurt performance, but worrying about that before measuring would be premature optimization.



回答3:

flush() flushes the iostream library's buffers - however the data is almost certainly not immediately flushed from the operating system's buffers at exactly the same time, so there is a small period during in which an operating system crash could lose you data. You can of course lose data at any time if you suffer a hard disk failure, whether the data was written or not, so I wouldn't worry too much about this.



回答4:

As long as flush() has returned, your program has successfully put the output in the OS's hands. Unless the OS (or disk) crashes, your data should be on disk next time the disk writes (note that the disk likely has a solid state cache of its own).

Until flush() returns, it's anybody's guess how much will make it to the disk.