File Stream Error Handling & State Flags

🟡 Intermediate

📖 Definition

C++ stream state flags monitor file I/O operations:

  • file.is_open(): Verifies file opened successfully.
  • file.fail(): Set when formatting or parsing errors occur.
  • file.eof(): Set when end-of-file is reached.
  • file.bad(): Set on unrecoverable hardware/I/O errors.

💡 Code Example

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("nonexistent.txt");

    if (!file.is_open()) {
        std::cerr << "Error: File could not be opened!\n";
    }
    return 0;
}