11.5 — Reading and writing files

📘 Chapter 11⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Writing to a file#

std::ofstream ("output file stream") works just like std::cout, but writes to a file:

C++▶ Run
#include <fstream> int main(){    std::ofstream out { "scores.txt" };    out << "Ana 90\n";    out << "Ben 75\n";    return 0;   // the file is closed automatically}

Reading from a file#

std::ifstream ("input file stream") works like std::cin:

C++▶ Run
#include <fstream>#include <iostream>#include <string> int main(){    std::ifstream in { "scores.txt" };    if (!in)    {        std::cout << "Could not open the file.\n";        return 1;    }     std::string name {};    int score {};    while (in >> name >> score)    {        std::cout << name << " scored " << score << '\n';    }    return 0;}
Output
Ana scored 90Ben scored 75

Reading line by line#

C++
std::string line {};while (std::getline(in, line)){    std::cout << line << '\n';}
Tip

The file is looked for in the program's working folder. If it "can't be found", that folder may be different from where your .cpp file is. Try a full path to check.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.