Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Strings and I/O

C++ std::ifstream and std::ofstream classes

Reference for std::ifstream and std::ofstream: open and check files, read lines or whole files, append, write binary data, open modes and error handling.

std::ifstream reads from a file and std::ofstream writes to one (header <fstream>). They are the one-directional specializations of std::fstream, and by far the most common way to do file I/O in C++. An ifstream is an std::istream, so >>, getline and read work on it. An ofstream is an std::ostream, so << and write work on it.

Opening is done in the constructor. If it fails (missing file, no permission, bad path) the stream is simply in a failed state, so test it before use. RAII closes the file for you when the stream goes out of scope, which also flushes pending output.

C++
std::ofstream out("log.txt");            // creates or truncates
std::ifstream in("log.txt");             // reads
if (!in) { /* open failed */ }

Try it

C++ Write lines, append, then read them back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Binary data and failed opens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
explicit std::ifstream(const std::filesystem::path& p, std::ios_base::openmode mode = std::ios::in);
explicit std::ofstream(const std::filesystem::path& p, std::ios_base::openmode mode = std::ios::out);

void open(const std::filesystem::path& p, std::ios_base::openmode mode);
bool is_open() const;
void close();

std::istream& read(char* buf, std::streamsize n);       // ifstream
std::streamsize gcount() const;
std::ostream& write(const char* buf, std::streamsize n);   // ofstream
Name Description
p Path of the file as a const char*, std::string or std::filesystem::path.
mode Open mode flags. ifstream always adds in; ofstream always adds out.
buf, n Raw bytes to read into or write from.

Common modes: std::ios::app (append), std::ios::trunc (the default for ofstream), std::ios::binary (no newline translation), std::ios::ate (position at the end after opening).

Returns: is_open() tells whether the file is open. gcount() returns how many bytes the last unformatted read extracted (it can be smaller than n at the end of the file).

Errors / undefined behavior: opening failures and I/O errors set failbit or badbit and never throw unless you enabled exceptions(). Casting arbitrary objects with reinterpret_cast<char*> and writing them is only meaningful for trivially copyable types, and the layout (size, padding, byte order) is not portable between machines.

Usage notes

  • Always check if (!in) after opening. Without it, a failed open looks like an empty file.
  • Choose the read style. in >> x for whitespace-separated values, std::getline for lines, read for bytes, std::istreambuf_iterator<char> to slurp the whole file into a string.
  • ofstream truncates by default. Use std::ios::app to add to the end or open with in | out through fstream to update in place.
  • Flushing. Output is buffered, so a crash can lose the last lines. The destructor, close() and flush() write them out. std::endl flushes on every line and slows large outputs.
  • Error at the end. To make sure all data reached the disk, close() the file and test out.fail() before it goes out of scope.
  • Where files go. Relative paths are relative to the process's working directory, which is not the executable's folder when you launch from an IDE.
  • Binary mode on Windows. Without std::ios::binary the library translates \n to \r\n on write and back on read, which corrupts binary data.
  • Large files. tellg() and seekg() use std::streamoff, which is 64-bit on modern platforms. Get the size of a file with std::filesystem::file_size instead of seeking to the end.
  • Streams are move-only. Return them from functions with return std::move(stream) or directly; copying is not possible.