File I/O in C++

From the C++ cheat sheet · File & Stream I/O · verified Jul 2026

File I/O

fstream and stringstream.

cpp
// Quick Reference
#include <fstream>
std::ofstream out("data.txt");
out << "hello\n";
std::ifstream in("data.txt");
std::string line;
std::getline(in, line);
💡 Streams are RAII - the file closes automatically when the fstream leaves scope.
⚡ Always check the stream (if (in)) - opening or reading can fail silently otherwise.
📌 std::getline reads a full line (past spaces); operator>> stops at whitespace.
🟢 std::stringstream is the idiomatic way to build or parse strings piece by piece.
file-iostreams
Back to the full C++ cheat sheet