#includeusing namespace std; int main() { ifstream myfile; myfile.open("example.txt"); if (!myfile.is_open()) { cout << "Error opening file" << endl; return 1; } // do something with the file myfile.clear(); // clear error flags myfile.seekg(0); // reset file position to beginning // do something else with the file myfile.close(); return 0; }
#includeThis example opens a file called "example.txt", reads integers from it using the extraction operator (>>), clears the error flags, resets the file position to the beginning, then reads the remaining lines of the file using getline and outputs them to the console. Package/library: Standard C++ library#include using namespace std; int main() { ifstream myfile; myfile.open("example.txt"); if (!myfile.is_open()) { cout << "Error opening file" << endl; return 1; } int num; while (myfile >> num) { cout << num << endl; } myfile.clear(); // clear error flags myfile.seekg(0); // reset file position to beginning string line; while (getline(myfile, line)) { cout << line << endl; } myfile.close(); return 0; }