Files and Streams
File Error Checks
A stream can be checked before reading so code can handle missing files safely.
File Error Checks
file_error_checks.cpp
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::string filename = ;
std::ofstream setup("present.txt");
setup << "status=ready" << std::endl;
setup.close();
std::remove("missing.txt");
std::ifstream input(filename);
if (input) {
std::string line;
std::getline(input, line);
std::cout << "opened=yes" << std::endl;
std::cout << line << std::endl;
} else {
std::cout << "opened=no" << std::endl;
std::cout << "fallback=use default" << std::endl;
}
std::remove("present.txt");
return 0;
}
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::string filename = ;
std::ofstream setup("present.txt");
setup << "status=ready" << std::endl;
setup.close();
std::remove("missing.txt");
std::ifstream input(filename);
if (input) {
std::string line;
std::getline(input, line);
std::cout << "opened=yes" << std::endl;
std::cout << line << std::endl;
} else {
std::cout << "opened=no" << std::endl;
std::cout << "fallback=use default" << std::endl;
}
std::remove("present.txt");
return 0;
}
stream state check
An input stream converts to `true` when the file opened successfully and to `false` when it did not.