File Streams


  • File stream class in C++
    • #include <fstream>

ifstream

#include <fstream>
 
int main() {
    ifstream fin;
    fin.open("text.txt"); // open file
    fin >> x;             // read file
    fin.close();          // close file
}

ofstream

#include <fstream>
 
int main() {
    ofstream fout;
    fout.open("text.txt"); // open file
    fout << x;             // write file
    fout.close();          // close file
}

Internal State Flags


fail()

fstream fin("test.txt"); // Assume text.txt contains a line "12345"
if (fin.fail()) {
    cout << "fail to open test.txt\\n";
    exit(1);
}
 
char buf[4];
fin.getline(buf, 4);
if (fin.fail()) {
    cout << "getline failed when reading from test.txt\\n";
    exit(1);
}

eof()

#include <fstream>
 
int main() {
    ifstream fin;
    fin.open("input.txt"); // abc
    char c;
    while (!fin.eof()) {   // it will read last char one more time
        fin >> c;          // try 'while (fin >> next)' instead
        cout << c;         // abcc
    }
}

clear()

fstream fin("input.txt"); // assume input.txt contains 2 lines
                          // line 1: 123456; line 2: 789
char buf[4];
int i = 0;
do {
    fin.getline(buf, 4);
    fin.clear(); // used to reset internal state flags
    cout << i++ << ": " << buf << "\\n";
    getchar(); // used to pause the program
} while (!fin.eof());