2011-02-18 86 views
6

如果我运行下面的代码,没有文件是在所有已创建:为什么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中的错误?

+3

什么版本的Visual Studio? – GManNickG 2011-02-18 02:11:12

回答

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()

0

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