Skip to content
  • File I/O with fstream · C++

File I/O with fstream

LearnViaNotes @learnvianotes· 2 min read

<fstream> gives you std::ofstream (write), std::ifstream (read) and std::fstream (both). They work exactly like cin/cout and close themselves (RAII).

Write, then read back

C++
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>

int main() {
    {
        std::ofstream out("scores.txt");                 // truncates / creates
        if (!out) { std::cerr << "cannot open\n"; return 1; }
        out << "ada 91\n" << "bob 78\n" << "cy 85\n";
    }                                                     // closed (and flushed) here

    {
        std::ofstream app("scores.txt", std::ios::app);  // append mode
        app << "dee 99\n";
    }

    std::ifstream in("scores.txt");
    std::string name;
    int score, total = 0, count = 0;
    while (in >> name >> score) {                         // token-by-token
        total += score;
        ++count;
    }
    std::cout << count << " students, average " << total / count << '\n';

    in.clear();                                           // reset EOF flag…
    in.seekg(0);                                          // …and rewind
    std::string line;
    std::getline(in, line);                               // line-by-line
    std::cout << "first line: " << line << '\n';
    in.close();
    std::remove("scores.txt");
}
Output
4 students, average 88
first line: ada 91
Mode flagMeaning
std::ios::in / std::ios::outRead / write (defaults for ifstream / ofstream)
std::ios::appEvery write goes to the end
std::ios::truncDiscard existing contents (default for ofstream)
std::ios::binaryNo newline translation (matters on Windows)
std::ios::ateStart at the end, but may seek anywhere

Stream state

CheckTrue when
if (stream) / !stream.fail()Last operation succeeded
stream.eof()Tried to read past the end
stream.fail()Format error or EOF (e.g. reading letters into an int)
stream.bad()Unrecoverable I/O error
stream.clear()Resets the flags so you can continue

Binary files & whole-file reads

C++
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>

int main() {
    std::vector<int> data{1, 2, 3, 1000000};
    {
        std::ofstream out("data.bin", std::ios::binary);
        out.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(int));
    }
    std::ifstream in("data.bin", std::ios::binary);
    std::vector<int> back(4);
    in.read(reinterpret_cast<char*>(back.data()), back.size() * sizeof(int));
    std::cout << in.gcount() << " bytes, last = " << back[3] << '\n';

    std::ofstream("note.txt") << "line one\nline two\n";
    std::ifstream t("note.txt");
    std::stringstream buffer;
    buffer << t.rdbuf();                                  // slurp the whole file
    std::cout << buffer.str().size() << " chars\n";
    std::remove("data.bin");
    std::remove("note.txt");
}
Output
16 bytes, last = 1000000
18 chars

Do you need to call close() on an fstream?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report