Why does ofstream require a flush?(为什么 ofstream 需要刷新?)
问题描述
如果我运行以下代码,则根本不会创建任何文件:
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 需要刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 ofstream 需要刷新?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30