Lesson 17 of 20Practical Modern C++25 min

Working with Files

File streams let a program preserve information after it closes. Use ofstream to write, ifstream to read, and fstream when both operations are needed.

Writing to a Text File

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

int main()
{
    ofstream outputFile("students.txt");

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

    outputFile << "S001,Alice,88
";
    outputFile << "S002,Ben,76
";

    cout << "Records saved." << endl;
    return 0;
}

Reading from a Text File

Load data line by line
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    ifstream inputFile("students.txt");
    string line;

    while (getline(inputFile, line))
    {
        cout << line << endl;
    }

    return 0;
}
File location

When you use a relative file name, Visual Studio normally creates or reads the file from the program’s working directory. Check the project’s debugging settings when the file is not where you expect it.

Practice task

Ask the user for a name and score, then append the values to a text file.

Lesson Summary

Save and load text data with ofstream, ifstream, and fstream.