File open check
- C++ course
- Intermediate
- Lesson 91/116
- 5 min
Learn file open checking with is_open().
Safe opening with is_open
After opening a file you check whether it succeeded with is_open(). If the file does not exist or permissions are missing, is_open() returns false.
Example: std::ifstream in("missing.txt"); if (in.is_open()) { /* read */ } else { std::cout << "Could not open"; }. This pattern lets the program report an error instead of crashing. If you call >> without checking, reading silently fails when the file is not open and the program behaves wrongly. That is why checking is_open() on every file open is a solid habit.
Handle a file that did not open
When is_open() returns false the program should print an error message and not read the file. Otherwise >> fails silently.
Example: if (!in.is_open()) { std::cout << "Error"; return 1; }. This ends the program early when the file is not found. The ! operator inverts the is_open() result. Some programs write if (in) to query the stream state; it gives a check similar to is_open(). Whichever you use, reading a file without an open check is not safe.
Practice Check a missing file
The starting code tries to open missing.txt (this file does not exist). Check with is_open(): print "Open" if open, otherwise "Closed".
Starter code
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("missing.txt");
// Check with is_open and print the status
return 0;
}Sample solution
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("missing.txt");
if (in.is_open()) {
std::cout << "Open";
} else {
std::cout << "Closed";
}
return 0;
}Expected output
Closed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does it mean when in.is_open() returns false?
std::ifstream in("none.txt");
if (in.is_open()) { /* read */ }- The file is too large
- The file is empty
- The file could not be opened Correct answer
- The file is already closed
Explanation: false means the file could not be opened.
2 Complete the is_open call
if (in.____()) { std::cout << "Open"; }
if (in.is_open()) { std::cout << "Open"; }
Explanation: is_open() checks whether the file is open.
3 Match each piece to its role
| Term | Meaning |
|---|---|
is_open() |
Open check |
if (in.is_open()) |
Safe open |
return 1 |
Exit on error |
!in.is_open() |
Not open check |