public member function
<fstream>

std::ifstream::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 ifstream 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
15
16
17
18
19
20
// print the content of a text file.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream ifs;

  ifs.open ("test.txt");

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}

Data races

Modifies the ifstream 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