C++ Files

Programs become much more useful when they can remember things after they close. In C++ you work with files using the <fstream> library, which lets you write text to a file, read it back later, and update it. On this page you will learn how to create, write to, and read from files using clear, beginner-friendly examples.

The fstream library

To work with files you first include the <fstream> header. It gives you three main classes that each handle a different job. Pick the one that matches what you want to do with the file.

ClassWhat it does
ofstreamOutput file stream: creates and writes to files
ifstreamInput file stream: reads from files
fstreamA combined stream that can both read and write

Writing to a file

To create a file and write text into it, open an ofstream with a file name. If the file does not exist, C++ creates it for you. You send text into the file with the << operator, exactly like you do with cout. Always close the file when you are finished so the data is saved properly.

Create and write to a file

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ofstream outFile("notes.txt");
  outFile << "Learning C++ files is fun.\n";
  outFile << "This is the second line.\n";
  outFile.close();

  cout << "Finished writing to notes.txt";
  return 0;
}
Note: Opening an existing file with ofstream erases its current contents. If you want to keep the old text and add to the end instead, open the file in append mode: ofstream outFile("notes.txt", ios::app);

Reading from a file

To read a file, open it with an ifstream. You can read it one line at a time using getline() inside a while loop. The loop keeps running as long as there is another line to read, and stops automatically at the end of the file.

Read a file line by line

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
  ifstream inFile("notes.txt");
  string line;

  while (getline(inFile, line)) {
    cout << line << "\n";
  }

  inFile.close();
  return 0;
}

Checking that a file opened

A file might fail to open, for example if the name is wrong or the file is missing. Before you trust the data, check whether the stream opened successfully with is_open(). This small habit prevents confusing bugs later.

Safely open a file

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
  ifstream inFile("scores.txt");

  if (!inFile.is_open()) {
    cout << "Could not open the file.";
    return 1;
  }

  string line;
  while (getline(inFile, line)) {
    cout << line << "\n";
  }
  inFile.close();
  return 0;
}
  • Include <fstream> before working with files.
  • Use ofstream to write and ifstream to read.
  • Use getline() to read a file one line at a time.
  • Always close() a file and check is_open() before reading.

Exercise: C++ Files

Which header must be included to use ifstream and ofstream for file handling in C++?