Learn C++
#include "ioformatting/file_io.hpp"

File I/O with fstream in C++

//concept

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.

//how it works
1

Open and check

std::ifstream in("data.txt"); then if (!in) handles the missing-file case — never read from an unopened stream.

2

Same operators as console

in >> x, std::getline(in, line), and out << value work exactly like their cin/cout counterparts.

3

Truncate vs append

std::ofstream out("log.txt"); erases existing content; add std::ios::app to keep it and append new lines.

4

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.

//example
#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;
}
Output
remember this
1The ofstream creates (or truncates) note.txt and writes one line into it.
2close() flushes and releases the file so the subsequent reader sees complete data.
3The ifstream reopens the same file and getline pulls the line back out for printing.
//use cases
Saving and loading program data (scores, settings, savegames) as text
Appending timestamped entries to log files with ios::app
Reading datasets line by line with the while-getline pattern
Always checking open-success before touching a stream's contents

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.