File I/O in C++

What is File I/O?

File I/O (Input/Output) allows your C++ programs to read data from files and write data to files. This is useful for saving data between program runs.

Sequential Access Files

Sequential access files (also called text files) store lines of text that your program can read in order, from beginning to end. They can be either:

Required Header


#include <fstream>

This header gives access to:

Opening Files

Use the open() function to connect a file object to a file:


ofstream outFile;
outFile.open("foods.txt");
            

You can check if it worked using is_open():


if (outFile.is_open()) {
    // success
}
            

Writing to Files

Each line written can represent a record. Records can contain multiple fields, separated by a special character like #.


outFile << "Pizza#9.99" << endl;
outFile << "Tacos#7.49" << endl;
            

Reading from Files

You can read full lines using getline(), or use >> to read word by word or field by field. Use eof() to detect the end of the file:


while (!inFile.eof()) {
    getline(inFile, line);
    // process line
}
            

Don't Forget!

How File Streams Compare to cin and cout

Code Walkthrough – Full Example

This program saves a list of foods and their prices to a file, then reads and displays them:


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

int main() {
    ofstream outFile("foods.txt");

    if (!outFile.is_open()) {
        cout << "Could not open file for writing." << endl;
        return 1;
    }

    outFile << "Pizza#9.99" << endl;
    outFile << "Burger#5.49" << endl;
    outFile << "Ice Cream#3.25" << endl;
    outFile.close();

    ifstream inFile("foods.txt");
    string line;

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

    cout << "Food Menu:\n";
    while (getline(inFile, line)) {
        size_t separator = line.find('#');
        string name = line.substr(0, separator);
        string price = line.substr(separator + 1);
        cout << "- " << name << ": $" << price << endl;
    }

    inFile.close();
    return 0;
}
            

Key Terms