Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to handle non-existing opened file with ifstream ?
#include <iostream>
#include <fstream>
int main() {
std::ifstream empty("empty.txt");
std::ifstream no_file("no_file.txt");
std::cout << "bool: " << (empty?"e 1":"e 0") << ' ' << (no_file?"n 1":"n 0") << '\n';
std::cout << "rdstate:" << (empty.rdstate()?"e 1":"e 0") << ' ' << (no_file.rdstate()?"n 1":"n 0") << '\n';
std::cout << "fail: " << (empty.fail()?"e 1":"e 0") << ' ' << (no_file.fail()?"n 1":"n 0") << '\n';
std::cout << "eof: " << (empty.eof()?"e 1":"e 0") << ' ' << (no_file.eof()?"n 1":"n 0") << '\n';
std::cout << "bad: " << (empty.bad()?"e 1":"e 0") << ' ' << (no_file.bad()?"n 1":"n 0") << '\n';
std::cout << "good: " << (empty.good()?"e 1":"e 0") << ' ' << (no_file.good()?"n 1":"n 0") << '\n';
int x;
empty >> x;
no_file >> x;
std::cout << "------------\n";
std::cout << "bool: " << (empty?"e 1":"e 0") << ' ' << (no_file?"n 1":"n 0") << '\n';
std::cout << "rdstate:" << (empty.rdstate()?"e 1":"e 0") << ' ' << (no_file.rdstate()?"n 1":"n 0") << '\n';
std::cout << "fail: " << (empty.fail()?"e 1":"e 0") << ' ' << (no_file.fail()?"n 1":"n 0") << '\n';
std::cout << "eof: " << (empty.eof()?"e 1":"e 0") << ' ' << (no_file.eof()?"n 1":"n 0") << '\n';
std::cout << "bad: " << (empty.bad()?"e 1":"e 0") << ' ' << (no_file.bad()?"n 1":"n 0") << '\n';
std::cout << "good: " << (empty.good()?"e 1":"e 0") << ' ' << (no_file.good()?"n 1":"n 0") << '\n';
empty >> x;
no_file >> x;
std::cout << "------------\n";
std::cout << "bool: " << (empty?"e 1":"e 0") << ' ' << (no_file?"n 1":"n 0") << '\n';
std::cout << "rdstate:" << (empty.rdstate()?"e 1":"e 0") << ' ' << (no_file.rdstate()?"n 1":"n 0") << '\n';
std::cout << "fail: " << (empty.fail()?"e 1":"e 0") << ' ' << (no_file.fail()?"n 1":"n 0") << '\n';
std::cout << "eof: " << (empty.eof()?"e 1":"e 0") << ' ' << (no_file.eof()?"n 1":"n 0") << '\n';
std::cout << "bad: " << (empty.bad()?"e 1":"e 0") << ' ' << (no_file.bad()?"n 1":"n 0") << '\n';
std::cout << "good: " << (empty.good()?"e 1":"e 0") << ' ' << (no_file.good()?"n 1":"n 0") << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.