为什么 ofstream 需要刷新?

2022-01-07 00:00:00 file stream standard-library c++

如果我运行以下代码,则根本不会创建任何文件:

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* close();
如果 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: 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().

相关文章