public member function
<fstream>

std::fstream::close

void close();
Close file
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 fstream object is destroyed.

Return Value

none

If the operation fails (including if no file was open before the call), the failbit state 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
// fstream::open / fstream::close
#include <fstream>      // std::fstream

int main () {

  std::fstream fs;
  fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);

  fs << " more lorem ipsum";

  fs.close();

  return 0;
}


Data races

Modifies the fstream 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.

See also