In C++, close() finishes work with a file. It writes out any text still waiting in the buffer and then disconnects the stream from the file.
The stream object stays alive and can open another file later with open(). If you forget to call it, the destructor does it for you when the stream goes out of scope. Include <fstream> to use it.
This is a member function of std::fstream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call close on a file stream. It takes no arguments.
C++
out << "data";
out.close(); // saved and disconnected
Call
What it does
out.close()
Saves the data and releases the file.
if (out.is_open()) out.close();
Closes only when the stream is open.
out.open("other.txt")
After close(), the same stream can be used with a new file.
Closing early is useful when you want to read a file that you just wrote with another stream.
Library declarations
C++
void close();
Parameters
Parameter
Description
None
close() takes no parameters.
Return Value
Return Value
Description
Nothing
close() returns void. If the stream was not open, or closing fails, failbit is set.
C++ Examples
Example 1 — is_open() Before and After close()
The stream knows whether it is connected. This program creates close_demo.txt.
std::ifstream in; creates a stream with no file attached.
in.close() has nothing to close, so it sets failbit.
is_open() was false all the time, and fail() now reports the mistake.
Frequently Asked Questions
It flushes the buffered data to the file and disconnects the file stream from the file.
No. The destructor of ofstream and ifstream closes the file when the stream goes out of scope. Call close() when you need the file free or saved earlier.
Yes. Call open() with a new file name. If failbit is set from an earlier problem, call clear() first.
The second close() has nothing to close and sets failbit. It is harmless but shows a mistake in the logic.
No. It only releases the connection. The file stays on the disk with the data that was written.