Closes the file currently associated with the object, disassociating it from the stream.
Any pending output sequence is written to the file.
If the stream is currently not associated with any file (i.e., no file has successfully been open with it), calling this function fails.
The file association of a stream is kept by its internal stream buffer:
Internally, the function calls rdbuf()->close(), and sets failbit in case of failure.
Note that any open file is automatically closed when the basic_ofstream object is destroyed.
Return Value
none
If the operation fails (including if no file was open before the call), the failbitstate flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ofstream::open / ofstream::close
#include <fstream> // std::ofstream
int main () {
std::ofstream ofs;
ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();
return 0;
}
Data races
Modifies the basic_ofstream object.
Concurrent access to the same stream may introduce data races.
Exception safety
Basic guarantee: if an exception is thrown, the stream is in a valid state.
Any exception thrown by an internal operation is caught by the function and rethrown after closing the file.
It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state.