Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 171 ยท Input/Output and Files

Reading and Writing Text Files

Read and write text files in C++ with ifstream, ofstream and fstream - open modes, checking for errors, reading line by line or word by word, and RAII closing.

Programs become much more useful once they can remember things between runs: settings, saved games, reports, logs. In C++ you read and write files with file streams from <fstream>. They're the same streams you already know from I/O Streams in Depth: << writes, >> and std::getline read, and the state flags tell you when something went wrong. If you can use std::cin and std::cout, you can already use files.

This lesson covers the three file stream classes, how to open files and check that it worked, the open modes (truncate, append and friends), the common ways to read text (line by line, word by word, all at once), and why you seldom need to call close() yourself.

In our editor every run starts with an empty folder, and files you create disappear when the program ends. That's why each example writes a file first and then reads it back in the same program. On your own computer, files stay on disk.

The three file stream classes

Class Direction Default mode Derives from
std::ofstream write out (create or truncate) std::ostream
std::ifstream read in std::istream
std::fstream read and write in | out std::iostream

Because they derive from the console stream classes, everything you write for std::ostream& works with files too. You can also use C++23's std::print and std::println with any std::ostream, including a file: std::println(file, "x = {}", x).

Writing and reading your first file

Creating an std::ofstream with a file name opens the file. If it doesn't exist, it's created; if it does, its old contents are erased first. Reading works the same way with std::ifstream.

C++ Write a file, then read it line by line

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.

Three habits in this small program are worth copying:

  • Check that the file opened. A stream converts to false if opening failed, exactly like after a failed read. Without the check, every later read silently does nothing.
  • Read with the read in the loop condition. while (std::getline(in, line)) stops cleanly at the end of the file, for the same reasons as while (std::cin >> x).
  • Let scope close the file. The inner { } block destroys out, which flushes and closes the file before we open it for reading. This is RAII at work.

You can also create the stream first and call open() later, check is_open(), and call close() to finish early. A closed stream can be opened again with another file.

C++
std::ofstream log;
log.open("app.log");
if (!log.is_open()) { /* handle the error */ }
log << "started\n";
log.close();               // optional; the destructor would do it

When opening fails

Opening fails for many reasons: the file doesn't exist, the folder doesn't exist, you lack permission, or the path names a directory. The stream itself only tells you that it failed. On Linux and macOS (and in practice on Windows), the C library also sets errno, which std::strerror turns into a message. The C++ standard doesn't promise this, so treat the message as a helpful extra.

C++ Detecting and explaining open failures

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.

Writing into no-such-folder/ fails because file streams never create directories. Create them first with std::filesystem::create_directories, which you'll meet in The Filesystem Library. That library can also check whether a file exists before you try to open it, though simply opening and checking is usually enough.

Open modes

The second constructor argument chooses the open mode, a combination of flags from std::ios joined with |:

Flag Meaning
std::ios::in Open for reading
std::ios::out Open for writing
std::ios::trunc Erase existing contents when opening
std::ios::app Append: every write goes to the end of the file
std::ios::ate Start positioned at the end, but you may move elsewhere
std::ios::binary No newline translation (see Binary Files)
std::ios::noreplace C++23: fail if the file already exists (exclusive create)

The most important difference is between truncating and appending. std::ofstream truncates by default, which is perfect for regenerating a report but disastrous for a log file. Pass std::ios::app to keep the old contents:

C++ Truncate versus append

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.

report.txt contains only the last run, while events.log has all three lines. The in.rdbuf() trick copies the whole file through the stream buffer in one statement; it's the quickest way to print a file.

std::fstream doesn't create a missing file when opened with only in | out; opening fails instead. Add std::ios::trunc (or app) when you want it created. This surprises many people.

Reading text in different ways

Pick the reading method that matches the file's structure:

  • Line by line with std::getline(in, line) for line-oriented formats: logs, CSV, configuration files.
  • Token by token with in >> value when the file is a sequence of whitespace-separated words or numbers. Newlines count as whitespace.
  • Character by character with in.get(c) when you need every character, including spaces.
  • All at once into a std::string when the file is small and you want to process it as a whole.
C++ Words, numbers and a whole file

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.

The extra spaces before grace don't bother >>, because it skips all leading whitespace. That's convenient, but it also means >> can't tell where one line ends and the next begins. When lines matter, read each line with getline and then parse the line, often with an std::istringstream from String Streams.

Reading a whole file with std::istreambuf_iterator is short and correct. For very large files, ask for the size first with std::filesystem::file_size and reserve the string, or read the file in chunks.

Processing a file: read, transform, write

Real programs often read one file and produce another. Here a simple comma-separated file of temperatures becomes a formatted report, and bad lines are reported instead of crashing the program:

C++ From a CSV file to a report

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.

Notice report.close() followed by a check. Normally the destructor closes the file, but a destructor can't report failure. If the final flush fails (disk full, network drive gone), only an explicit close() lets you notice it by testing the stream afterwards. For important output, close explicitly and check; for everything else, let RAII do it.

Text mode and newlines

File streams open in text mode by default. On Linux and macOS, text and binary mode are identical. On Windows, text mode translates '\n' to the two bytes \r\n when writing and back when reading, and treats byte 26 (Ctrl+Z) as end of file. That's correct for text, but it corrupts non-text data, so open such files with std::ios::binary, as you'll do in Binary Files.

A related portability trap: a file written on Windows and read on Linux keeps its \r characters, so getline returns lines ending in '\r'. Robust readers strip a trailing '\r' when it's present:

C++
while (std::getline(in, line)) {
    if (!line.empty() && line.back() == '\r') {
        line.pop_back();
    }
    // ... use line ...
}

File paths

The constructors accept a std::string, a C string, or a std::filesystem::path. Relative paths like "data/input.txt" are resolved against the program's current working directory, which is where it was started from, not necessarily where the executable lives. That's a common reason why "the file is right there" but opening fails. Forward slashes work as separators on every platform, including Windows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. report.txt contains 10 lines. What happens after std::ofstream out("report.txt"); out << "hi\n";?

    ofstream opens with out | trunc by default, so the old contents are erased. Use std::ios::app to append.
  2. 2. Which loop correctly reads every line of a file?

    Putting getline in the condition means the body only runs after a successful read. The eof() and while (in) versions process one extra, failed read.
  3. 3. A file contains ada 120. What do in >> name >> points produce?

    Formatted extraction skips any whitespace before each value, including spaces, tabs and newlines.
  4. 4. Why would you call close() explicitly on an ofstream instead of relying on the destructor?

    The destructor flushes and closes too, but silently. After close() you can test the stream's state.
  5. 5. std::ofstream out("logs/today.txt"); fails, and the folder logs doesn't exist. What's the fix?

    File streams create files but never directories.

Summary

  • std::ofstream writes, std::ifstream reads and std::fstream does both; they work like cout and cin, and std::println(file, ...) works too.
  • Always check that a file opened (if (!file)); std::strerror(errno) usually explains why it didn't.
  • ofstream truncates by default; use std::ios::app to append. fstream with in | out won't create a missing file.
  • Read with getline for lines, >> for tokens, get for characters, or istreambuf_iterator/rdbuf() for the whole file.
  • Destructors close files automatically; call close() and check the stream when a write failure matters.
  • Text mode translates newlines on Windows; strip stray '\r' and use binary mode for non-text data.

Next: Binary Files, where you'll write raw bytes, jump around with seekg, and deal with endianness.