C++ Files
Programs often need to save data so it survives after they exit, or load data someone else prepared. C++ handles files with file streams from the <fstream> header. They work just like cout and cin, so everything you know about <<, >> and getline carries over.
| Class | Purpose |
|---|---|
std::ofstream |
output file stream — write to a file |
std::ifstream |
input file stream — read from a file |
std::fstream |
both reading and writing |
Note: The examples below create a small file in the program's working directory on the compiler server, then read it back. On your own computer the file appears next to where you run the program.
Writing a file
Create an ofstream with a file name. If the file does not exist it is created; if it does, it is overwritten. The file is closed automatically when the stream object goes out of scope:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
{
ofstream out("shopping.txt");
if (!out) {
cout << "Could not open file for writing\n";
return 1;
}
out << "milk\n";
out << "bread\n";
out << "eggs " << 12 << "\n";
} // out is closed here
ifstream in("shopping.txt");
string line;
while (getline(in, line)) {
cout << "> " << line << "\n";
}
}> milk
> bread
> eggs 12
The while (getline(in, line)) loop is the standard way to read a file line by line: getline returns the stream, which converts to false once there is nothing more to read.
Checking that a file opened
Opening can fail — the file may not exist, or you may lack permission. Always check the stream before using it, either with if (!stream) or stream.is_open():
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("this_file_does_not_exist.txt");
if (!in.is_open()) {
cout << "Error: file not found\n";
} else {
cout << "Opened successfully\n";
}
}Error: file not found
Appending and reading values
Pass ios::app to add to the end of an existing file instead of replacing it. When reading, >> extracts whitespace-separated values directly into variables:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream("scores.txt") << "ana 81\nben 67\n"; // create the file
{
ofstream log("scores.txt", ios::app); // append mode
log << "cleo 94\n";
}
ifstream in("scores.txt");
string name;
int score, total = 0, count = 0;
while (in >> name >> score) {
cout << name << " scored " << score << "\n";
total += score;
count++;
}
cout << "Average: " << static_cast<double>(total) / count << "\n";
}ana scored 81
ben scored 67
cleo scored 94
Average: 80.6667
Parsing CSV-like data
Combine getline on the file with a stringstream on each line to split fields on a delimiter:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct Item {
string name;
int qty;
double price;
};
int main() {
{
ofstream out("stock.csv");
out << "name,qty,price\n";
out << "widget,4,2.50\n";
out << "gadget,10,0.99\n";
out << "doohickey,1,15.00\n";
}
ifstream in("stock.csv");
string line;
getline(in, line); // skip the header row
vector<Item> items;
while (getline(in, line)) {
stringstream ss(line);
string name, qty, price;
getline(ss, name, ',');
getline(ss, qty, ',');
getline(ss, price, ',');
items.push_back({name, stoi(qty), stod(price)});
}
double value = 0;
for (const auto& it : items) {
cout << it.name << ": " << it.qty << " @ " << it.price << "\n";
value += it.qty * it.price;
}
cout << "Stock value: " << value << "\n";
}widget: 4 @ 2.5
gadget: 10 @ 0.99
doohickey: 1 @ 15
Stock value: 34.9
Open modes
| Mode | Meaning |
|---|---|
ios::in |
open for reading (default for ifstream) |
ios::out |
open for writing, truncating the file (default for ofstream) |
ios::app |
append — every write goes to the end |
ios::binary |
binary mode, no newline translation |
ios::trunc |
discard existing contents |
Combine modes with |, for example fstream f("data.bin", ios::in | ios::out | ios::binary);.
Tip: For working with paths, directories and file sizes, C++17 added
<filesystem>:std::filesystem::exists("x.txt"),std::filesystem::file_size(...),create_directory(...)and more.
Test yourself
Which class do you use to write text to a file?
- ifstream
- ofstream
- iostream
- filebuf
What happens when you open an existing file with a plain ofstream out("a.txt");?
- New data is appended
- The old contents are erased
- It fails to open
- It opens read-only
What is the idiomatic way to read a file line by line?
- while (!in.eof()) { getline(in, line); }
- while (getline(in, line)) { ... }
- for (line : in)
- in.readAll()