Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ofstream require a flush?

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?

like image 310
Brent Arias Avatar asked Feb 18 '11 01:02

Brent Arias


People also ask

How do you flush ofstream?

In oder to force all buffered writes to take place immediately, you can flush the stream. You can do this either directly by invoking the flush() method or through the std::flush stream manipulator: std::ofstream os("foo. txt"); os << "Hello World!" << std::flush; char data[3] = "Foo"; os.

Does exit flush?

std::exit() destroys objects with static storage duration (thereby flushing such ofstream objects). It does not destroy objects with automatic storage duration (leaving such ofstream objects unflushed).

Does file close flush C++?

This article focuses on closing the file. In a case, if a C++ program terminates, then it automatically flushes out all the streams, releases all the allocated memory, and closes all the opened files.

Does ofstream automatically close?

Note that any open file is automatically closed when the ofstream object is destroyed.


1 Answers

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

like image 72
GManNickG Avatar answered Nov 05 '22 09:11

GManNickG