Why does ofstream require a flush?

妖精的绣舞 提交于 2019-11-30 04:22:26

问题


If I run the following code, no file is created at all:

std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);
outputFile.write((const char*)lpResLock, dwSizeRes);
outputFile.close();

However, if I add a flush() before the close, it works:

std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);
outputFile.write((const char*)lpResLock, dwSizeRes);
outputFile.flush();
outputFile.close();

Does the standard library actually require this, or is it a bug in the Visual C++ CRT?


回答1:


It's a bug. Reading §27.8.1.10/4, abridged:

void close();
Effects: Calls rdbuf()->close()...

What does rdbuf()->close() do? According to §27.8.1.3/6, abridged, emphasis mine:

basic_filebuf<charT,traits>* close();
If is_open() == false, returns a null pointer. If a put area exists, calls overflow(EOF) to flush characters. ...

That is, it's suppose to flush. (Indeed, the call to flush() ultimately does the same thing.)


Note the call to close() itself isn't needed, as the destructor of basic_ofstream will call close().




回答2:


Are you checking the file before you exit from the program? OS will buffer all IO, so may not see any data(unless you flush) in the file before you exit.



来源:https://stackoverflow.com/questions/5036878/why-does-ofstream-require-a-flush

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