← C++ Index

📁 <fstream> — File I/O Streams

C++ file I/O through stream classes. Files close automatically when the object goes out of scope (RAII). ifstream reads, ofstream writes, fstream does both.

Include: #include <fstream> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::ifstreamclass : istreamInput file stream (reading)
std::ofstreamclass : ostreamOutput file stream (writing)
std::fstreamclass : iostreamBidirectional file stream
fs.open(path, mode)voidOpen file; mode = ios::in | ios::out | ios::app | ios::binary
fs.close()voidClose the file
fs.is_open()boolTrue if file was opened successfully
fs.good()boolTrue if no error flags set
fs.eof()boolTrue if end-of-file reached
fs.fail()boolTrue if a non-fatal error occurred
fs >> xistream &Extract next token from file
fs << xostream &Write x to file
getline(fs, str)istream &Read a full line into str
fs.seekg(pos)istream &Set read position
fs.seekp(pos)ostream &Set write position
ios::inopenmodeOpen for reading
ios::outopenmodeOpen for writing (truncates)
ios::appopenmodeAppend to end of file
ios::binaryopenmodeOpen in binary mode

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main() {
    { // Write
        ofstream out("students.txt");
        if (!out) { cerr << "Cannot open for writing\n"; return 1; }
        out << "Alice 95\nBob   87\nCarol 92\n";
    } // file closes here (RAII)

    { // Read line by line
        ifstream in("students.txt");
        string line;
        cout << "Contents:\n";
        while (getline(in, line)) cout << "  " << line << "\n";
    }

    { // Append
        ofstream app("students.txt", ios::app);
        app << "Dave  78\n";
    }

    // Parse into struct
    struct Student { string name; int score; };
    vector<Student> students;
    ifstream in2("students.txt");
    string name; int score;
    while (in2 >> name >> score) students.push_back({name, score});

    cout << "\nParsed " << students.size() << " students.\n";
    for (auto &s : students)
        cout << "  " << s.name << " => " << s.score << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o fstream_demo fstream_demo.cpp

← <algorithm>  |  🏠 Index  |  <sstream> →