如果我运行以下代码,根本不会创建任何文件:
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();
Effects: Callsrdbuf()->close()
...
什么是rdbuf()->close()
做?根据 §27.8.1.3/6,删节,强调我的:
basic_filebuf<charT,traits>* close();
Ifis_open() == false
, returns a null pointer. If a put area exists, callsoverflow(EOF)
to flush characters. ...
也就是说,它应该冲洗。 (实际上,调用 flush()
最终会做同样的事情。)
请注意对 close()
的调用本身不需要,因为 basic_ofstream
的析构函数会调用close()
.
关于c++ - 为什么 ofstream 需要冲洗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5036878/