In C++, is_open() tells you whether a file stream is currently connected to a file. It returns true after a successful open and false before opening, after close(), and when opening failed.
It is the standard check after trying to open a file, for example to read a file that may not exist. 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 is_open on an ifstream, ofstream, or fstream. It takes no arguments.
C++
std::ifstream in("notes.txt");
if (!in.is_open()) {
std::cerr << "cannot open notes.txt\n";
return 1;
}
Call
What it does
in.is_open()
Returns true when a file is open.
!in.is_open()
True when opening failed or the stream is closed.
if (!in)
A shorter test. It checks the stream flags instead, but it is also true for a failed open.
Check is_open() right after opening. Reading from a stream that never opened just fails quietly.
Library declarations
C++
bool is_open() const;
Parameters
Parameter
Description
None
is_open() takes no parameters.
Return Value
Return Value
Description
true
The stream is attached to an open file.
false
No file is open: never opened, opening failed, or already closed.
C++ Examples
Example 1 — is_open() Through the Life of a Stream
Check before opening, after opening, and after closing. The program creates is_open_demo.txt.
save() opens an ofstream with the given name and uses is_open() to decide what to return.
The first name is in the current folder, so the file opens and the function returns true.
The second name points into a folder that does not exist. The open fails, is_open() is false, and the function returns false.
Frequently Asked Questions
It returns true if the file stream is attached to an open file, and false if not.
Almost. Both are false when opening failed. But if (file) also becomes false after a failed read, while is_open() stays true as long as the file is open.
The file may not exist, the path may be wrong, or you may have no permission. Check the file name and the folder from which the program runs.
No. It exists only on file streams (ifstream, ofstream, fstream) and the file buffer.
Not required, but closing a stream that is not open sets failbit. A check like if (out.is_open()) avoids that.