Skip to content
AgileLogics
4 min read

File I/O with Streams

Prerequisites: Lambda expressions

<fstream> provides file streams that work like std::cout/ std::cin, and are themselves RAII types — no manual fclose needed.

#include <fstream>

std::ofstream out("notes.txt");
out << "Hello, file!" << std::endl;
out.close(); // optional — the destructor closes it anyway

std::ifstream in("notes.txt");
std::string line;
while (std::getline(in, line)) {
    std::cout << line << std::endl;
}

Common mistakes

  • Not checking out.is_open() (or the stream's boolean state) before writing — a stream that failed to open (bad path, permissions) silently does nothing on every write instead of throwing by default.