C++ by Example
C++ by Example

File I/O

1 min read

File I/O

C++ provides stream-based file I/O through <fstream>. The same << and >> operators used with std::cout and std::cin work with file streams.

Writing a text file

#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::ofstream file("output.txt");

    if (!file.is_open()) {
        std::cerr << "Failed to open file\n";
        return 1;
    }

    file << "Line 1\n";
    file << "Line 2\n";
    file << "Value: " << 42 << "\n";
}   // file closes automatically when it goes out of scope

Reading a text file

#include <fstream>
#include <string>
#include <iostream>

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

    if (!file) {
        std::cerr << "Cannot open file\n";
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << "\n";
    }
}

Reading word by word

>> reads one whitespace-delimited token at a time:

std::ifstream file("words.txt");
std::string word;
while (file >> word) {
    std::cout << "[" << word << "]\n";
}

Reading the entire file at once

#include <fstream>
#include <sstream>
#include <string>

std::string read_all(const std::string& path) {
    std::ifstream file(path);
    std::ostringstream oss;
    oss << file.rdbuf();
    return oss.str();
}

Or with iterators:

std::string content(
    std::istreambuf_iterator<char>(file),
    std::istreambuf_iterator<char>()
);

Open modes

// Append to existing file instead of overwriting
std::ofstream log("app.log", std::ios::app);

// Open for both reading and writing
std::fstream rw("data.txt", std::ios::in | std::ios::out);

// Truncate (default for ofstream, but explicit here)
std::ofstream out("data.txt", std::ios::trunc);

Common mode flags:

Flag Meaning
std::ios::in Open for reading
std::ios::out Open for writing
std::ios::app Append to end
std::ios::trunc Truncate to zero on open
std::ios::binary Binary mode (no newline translation)

Binary files

#include <fstream>

struct Record {
    int id;
    double value;
};

int main() {
    // Write binary
    std::ofstream out("data.bin", std::ios::binary);
    Record r = {1, 3.14};
    out.write(reinterpret_cast<const char*>(&r), sizeof(r));

    // Read binary
    std::ifstream in("data.bin", std::ios::binary);
    Record r2;
    in.read(reinterpret_cast<char*>(&r2), sizeof(r2));
    std::cout << r2.id << " " << r2.value << "\n";   // 1 3.14
}

reinterpret_cast<const char*> converts the struct pointer to a byte pointer for raw I/O.

Checking for errors

std::ofstream file("data.txt");
if (!file) { /* open failed */ }

file << data;
if (!file) { /* write failed */ }

if (file.fail()) { /* any error flag set */ }
if (file.eof())  { /* end of file reached */ }
C++ by Example
C++ by Example

Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.

View book →