#include#include int main() { std::ifstream file("example.txt"); if(file.fail()) { std::cerr << "Failed to open file!" << std::endl; return 1; } // read file contents... if(file.eof()) { // end of file reached without error std::cout << "End of file reached." << std::endl; } else if(file.fail()) { // error occurred while reading std::cerr << "Error while reading file!" << std::endl; file.clear(); // clear error flags } file.close(); return 0; }
#includeIn this example, we again attempt to open a file named "example.txt" and check for any errors. We then proceed to read integer values from the file and compute their sum. If an error occurs during reading, we print an error message and clear the error flags of the file stream using `file.clear()`. We then print the sum of the integers read from the file. The `#include int main() { std::ifstream file("example.txt"); if(file.fail()) { std::cerr << "Failed to open file!" << std::endl; return 1; } int value; // read integers from file and print their sum int sum = 0; while(file >> value) { sum += value; } if(file.fail()) { std::cerr << "Error while reading file!" << std::endl; file.clear(); // clear error flags } std::cout << "Sum: " << sum << std::endl; file.close(); return 0; }