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

廉价感情. 提交于 2019-12-18 12:59:09

问题


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.



来源:https://stackoverflow.com/questions/2341177/c-stdofstream-flush-but-not-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!