为什么ofstream需要刷新?

时间:2011-02-18 01:52:21

标签: c++ file stream standard-library

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

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中的错误?

2 个答案:

答案 0 :(得分:8)

这是一个错误。阅读§27.8.1.10/ 4,删节:

  

void close();
  效果:致电rdbuf()->close() ...

rdbuf()->close()做什么?根据§27.8.1.3/ 6,删节,强调我的:

  

basic_filebuf<charT,traits>* close();
  如果is_open() == false,则返回空指针。 如果存在放置区域,请拨打overflow(EOF)以刷新字符。 ...

也就是说,它应该冲洗。 (实际上,对flush()的调用最终会做同样的事情。)


请注意,不需要调用close()本身,因为basic_ofstream的析构函数会调用close()

答案 1 :(得分:0)

您是否在退出程序之前检查文件?操作系统将缓冲所有IO,因此在退出之前可能看不到文件中的任何数据(除非您刷新)。