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 需要刷新?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
