为什么stream需要刷新? [英] Why does ofstream require a flush?
问题描述
如果我运行以下代码,则不会创建任何文件:
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();
标准库实际上是否需要这个,还是Visual C ++ CRT中的一个错误? p>
Does the standard library actually require this, or is it a bug in the Visual C++ CRT?
推荐答案
这是一个错误。阅读§27.8.1.10/ 4,缩写:
It's a bug. Reading §27.8.1.10/4, abridged:
void close();
效果:调用rdbuf() - > close()
...
rdbuf() - > close()
是什么?根据§27.8.1.3/ 6,简明,强调我:
What does rdbuf()->close()
do? According to §27.8.1.3/6, abridged, emphasis mine:
basic_filebuf< charT,traits> * close ();
如果is_open()== false
,则返回一个空指针。 如果存在放置区域,则调用overflow(EOF)
以刷新字符。 ...
basic_filebuf<charT,traits>* close();
Ifis_open() == false
, returns a null pointer. If a put area exists, callsoverflow(EOF)
to flush characters. ...
也就是说,假设要刷新。 (确实,调用 flush()
最终也会做同样的事情。)
That is, it's suppose to flush. (Indeed, the call to flush()
ultimately does the same thing.)
注意,不需要调用 close()
本身,因为 basic_ofstream
的析构函数调用 close()
。
Note the call to close()
itself isn't needed, as the destructor of basic_ofstream
will call close()
.
这篇关于为什么stream需要刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!