问题描述
如果我运行以下代码,则根本不会创建任何文件:
std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);outputFile.write((const char*)lpResLock, dwSizeRes);outputFile.close();
但是,如果我在关闭之前添加一个flush(),它会起作用:
std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);outputFile.write((const char*)lpResLock, dwSizeRes);outputFile.flush();outputFile.close();
标准库是否真的需要这个,还是 Visual C++ CRT 中的一个错误?
这是一个错误.阅读第 27.8.1.10/4 节,删节:
<块引用>void close();
效果:调用 rdbuf()->close()
...
rdbuf()->close()
有什么作用?根据第 27.8.1.3/6 节,删节,强调我的:
basic_filebuf
如果 is_open() == false
,则返回空指针.如果放置区域存在,则调用overflow(EOF)
来刷新字符. ...
也就是说,它应该刷新.(实际上,对 flush()
的调用最终会做同样的事情.)
请注意,不需要调用 close()
本身,因为 basic_ofstream
的析构函数将调用 close()
.>
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?
It's a bug. Reading §27.8.1.10/4, abridged:
void close();
Effects: Callsrdbuf()->close()
...
What does rdbuf()->close()
do? According to §27.8.1.3/6, abridged, emphasis mine:
basic_filebuf<charT,traits>* close();
Ifis_open() == false
, returns a null pointer. If a put area exists, callsoverflow(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()
.
这篇关于为什么 ofstream 需要刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!