Learning Hub Search Ctrl K

Legacy C++ › 5. Exceptions, Strings and I/O

File I/O

ifstream/ofstream, text vs binary, seeking and error states.

beginner #fstream#files#binary#text#seekg#error-handling

Explanation

<fstream> provides std::ifstream (read), std::ofstream (write) and std::fstream (both). They are RAII objects: the file closes automatically when the stream is destroyed. They share the whole stream interface with cin/cout.

Open modes (combine with |): std::ios::in, out, app (append), trunc (empty on open), binary (no newline translation), ate (seek to end).

  • Text mode uses <<, >> and getline.
  • Binary mode uses read(char*, n) / write(const char*, n).
  • seekg/tellg move the read position; seekp/tellp the write position.
  • Always check that the open succeeded: if (!file).

Example

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

struct Record { int id; double score; };

int main() {
    // --- text ---
    {
        std::ofstream out("scores.txt");
        if (!out) { std::cerr << "cannot open for writing\n"; return 1; }
        out << "Ann 91.5\nBob 78\n";
    }                                               // closed here

    std::ifstream in("scores.txt");
    std::string name; double score;
    while (in >> name >> score)
        std::cout << name << " -> " << score << "\n";

    // --- binary ---
    Record r = {7, 99.5};
    std::ofstream bout("data.bin", std::ios::binary);
    bout.write(reinterpret_cast<const char*>(&r), sizeof(r));
    bout.close();

    Record back = {0, 0};
    std::ifstream bin("data.bin", std::ios::binary);
    bin.read(reinterpret_cast<char*>(&back), sizeof(back));
    std::cout << back.id << " " << back.score << "\n";

    bin.seekg(0, std::ios::end);
    std::cout << "size: " << bin.tellg() << " bytes\n";
    return 0;
}

Common pitfalls

  • Not checking if (!file) after open hides missing files and permissions problems.
  • Using text mode for binary data on Windows corrupts bytes (\n ↔ \r\n, 0x1A).
  • Writing a struct directly with write is not portable: padding, endianness and pointers make it fragile. Fine for quick local files, not for formats.
  • Forgetting to flush()/close() before reading the same file back through another stream.
  • Reusing a stream after an error without clear().

Legacy vs modern

C++11 allows std::string file names in constructors (C++03 requires .c_str()), and C++17’s std::filesystem handles paths, directories and file sizes.

Exercises

1. How do you append to an existing text file?

std::ofstream out("log.txt", std::ios::app);