File I/O with fstream in C++
The <fstream> types — std::ifstream (read), std::ofstream (write), std::fstream (both) — are streams, so every <<, >>, and getline skill transfers directly from console I/O. Opening is one line (std::ifstream in("data.txt");), and the stream converts to false if the file couldn't be opened, which you must check before reading.
An ofstream truncates by default (wiping existing content) — pass std::ios::app to append instead. Files close automatically when the stream object dies (RAII), so explicit close() is optional except when you need the file released early.
Open and check
std::ifstream in("data.txt"); then if (!in) handles the missing-file case — never read from an unopened stream.
Same operators as console
in >> x, std::getline(in, line), and out << value work exactly like their cin/cout counterparts.
Truncate vs append
std::ofstream out("log.txt"); erases existing content; add std::ios::app to keep it and append new lines.
RAII closes for you
The destructor closes the file when the stream goes out of scope — explicit close() only matters for early release or error checking.
#include <iostream>#include <fstream>#include <string> int main() { std::ofstream out("note.txt"); out << "remember this" << std::endl; out.close(); std::ifstream in("note.txt"); std::string line; std::getline(in, line); std::cout << line << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.