C++ · Intermediate level

Intermediate level · Module 4: Files, Streams and Exceptions in C++ · Lesson 1 of 3

Reading and Writing Files

Open files with ifstream and ofstream, check that they opened, and read and write line by line.

In this lesson you will

  • Read and write text files with file streams
  • Check stream state and report failures

Key concepts

std::ifstreamstd::ofstreamis_open and stream statestd::filesystem::path

The lesson

std::ifstream in{"stock.csv"}; opens a file for reading, and std::ofstream out{"reorder.csv"}; for writing. Always check that a file opened — if (!in) — and report the file name; a wrong path is the most common file error.

Read line by line with while (std::getline(in, line)). The loop stops at the end of the file or when reading fails, so there is no need to test eof() separately.

File streams close automatically when they go out of scope (RAII). std::filesystem::path builds paths portably, and std::filesystem::exists checks for a file before opening it.

Step by step

  1. Open a stock file and print each line with its line number.
  2. Try a wrong file name and print a clear error.
  3. Write selected lines to a new file.
  4. Use std::filesystem to check the file exists first.

Practice activity

Write a program that copies only the lines containing a search word from one file to another and reports how many were copied.

Expected result: The output file contains exactly the matching lines, and a missing input file produces a clear message.

Check your understanding

  1. How do you check that a file opened successfully?

    Show answer

    Test the stream, for example if (!in) { … }.

  2. Do you need to call close() on an ifstream?

    Show answer

    No; it closes automatically when it goes out of scope.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.