C++ File Handling

C++ file handling means reading data from files and writing data to files. It uses stream classes from <fstream>, so working with a file feels similar to using std::cout and std::cin.

Files let a program keep data after the program ends. You can write settings, logs, reports, saved game data, or any text that should be available later.

File Stream Classes

The <fstream> header provides three common classes:

  • std::ofstream writes output to a file.
  • std::ifstream reads input from a file.
  • std::fstream can read and write using one stream object.

Like other C++ standard library types, file streams use RAII. When a file stream object goes out of scope, its destructor closes the file automatically. You can still call close() yourself when you want to finish using the file earlier.

Opening And Checking A File

You can pass a file name to the stream constructor. After opening, check the stream before using it. If the file cannot be opened, the stream will be in a failed state.

For input, a common pattern is to create an std::ifstream, then test it with if (!input) before reading. For output, create an std::ofstream, then test it with if (!output) before writing.

File names are usually relative to the directory where the program is run. For example, "data.txt" means a file named data.txt in the current working directory.

Example: Write Then Read A File

This program creates a small text file, writes two lines to it, closes it, and then reads the same file line by line.

#include <fstream>
#include <iostream>
#include <string>

int main(void) {
    std::ofstream output("courses.txt");

    if (!output) {
        std::cout << "Could not create file" << std::endl;
        return 1;
    }

    output << "C++ Basics" << std::endl;
    output << "C++ File Handling" << std::endl;
    output.close();

    std::ifstream input("courses.txt");

    if (!input) {
        std::cout << "Could not open file" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(input, line)) {
        std::cout << line << std::endl;
    }

    return 0;
}

Output:

C++ Basics
C++ File Handling

How The Example Works

std::ofstream output("courses.txt") opens a file for writing. If the file does not exist, C++ creates it. If it already exists, the default behavior is to replace its contents.

The program checks if (!output) before writing. This protects the program from silently continuing after a failed open operation, such as when the directory is not writable.

The insertion operator << writes text to the file, just like it writes text to std::cout. Each std::endl writes a newline and flushes the stream.

After writing, output.close() closes the output file before the program opens it for reading. Then std::ifstream input("courses.txt") opens the file as input. The loop while (std::getline(input, line)) keeps reading until there are no more complete lines to read.

Common File Modes

File modes control how a file is opened. They are passed as a second argument to the stream constructor or open().

Mode Meaning
std::ios::out Open for writing.
std::ios::in Open for reading.
std::ios::app Append new output to the end of the file.
std::ios::trunc Discard existing contents when opening.
std::ios::binary Open in binary mode instead of text mode.

For example, std::ofstream log("app.log", std::ios::app); opens a file so new text is added to the end instead of replacing old text.

Guidelines

  • Include <fstream> when using file streams.
  • Check that a file opened successfully before reading or writing.
  • Use std::getline() when you want to read a whole line, including spaces.
  • Use append mode for logs or history files that should keep old content.
  • Let stream objects close files automatically, or call close() when you need to reopen the same file immediately.

Takeaway: C++ file handling uses stream objects, so writing and reading files follows the same basic style as console input and output.