Beyond the Basics
File I/O with fstream
Read and write files the C++ way with ifstream, ofstream and fstream: modes, line-by-line reading, parsing records with stringstream, and binary files.
C++ file handling uses streams, exactly like cin and cout. Include <fstream>:
| Class | Purpose |
|---|---|
ofstream |
write to a file (output) |
ifstream |
read from a file (input) |
fstream |
both |
Writing and reading text
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream out("notes.txt"); // creates or truncates the file
if (!out) { cerr << "cannot open file" << endl; return 1; }
out << "Templates make code generic." << endl;
out << "Exceptions separate error handling." << endl;
out << "RAII frees resources automatically." << endl;
out.close();
ifstream in("notes.txt");
string line;
int n = 0;
while (getline(in, line)) // read until end of file
cout << ++n << ": " << line << endl;
return 0; // in closes automatically (RAII)
}1: Templates make code generic. 2: Exceptions separate error handling. 3: RAII frees resources automatically.
File modes
| Flag | Meaning |
|---|---|
ios::in |
open for reading |
ios::out |
open for writing (truncates by default) |
ios::app |
append: every write goes to the end |
ios::ate |
start at the end, but allow moving around |
ios::trunc |
erase existing contents |
ios::binary |
binary mode (no newline translation) |
Combine flags with |: fstream f("data.txt", ios::in | ios::out);
Reading structured records
Write records as text, then read them back with >> or parse each line with a stringstream:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
ofstream out("students.csv");
out << "roll,name,marks\n101,Asha,88\n102,Ravi,93\n103,Meera,79\n";
out.close();
ifstream in("students.csv");
string line;
getline(in, line); // skip the header
double total = 0;
int count = 0;
cout << left << setw(6) << "Roll" << setw(8) << "Name" << "Marks" << endl;
while (getline(in, line)) {
stringstream ss(line);
string roll, name, marksText;
getline(ss, roll, ','); // split on commas
getline(ss, name, ',');
getline(ss, marksText, ',');
int marks = stoi(marksText);
cout << setw(6) << roll << setw(8) << name << marks << endl;
total += marks;
count++;
}
cout << "Average: " << fixed << setprecision(2) << total / count << endl;
ofstream log("students.csv", ios::app); // append a new record
log << "104,Kiran,85\n";
return 0;
}Roll Name Marks 101 Asha 88 102 Ravi 93 103 Meera 79 Average: 86.67
Binary files
Binary I/O writes raw bytes — compact and fast, but not human-readable:
#include <iostream>
#include <fstream>
using namespace std;
struct Reading { int sensor; double value; };
int main() {
Reading data[3] = {{1, 21.5}, {2, 22.25}, {3, 19.75}};
ofstream out("readings.bin", ios::binary);
out.write(reinterpret_cast<const char *>(data), sizeof(data));
out.close();
ifstream in("readings.bin", ios::binary);
in.seekg(sizeof(Reading) * 2); // jump to the third record
Reading r;
in.read(reinterpret_cast<char *>(&r), sizeof(r));
cout << "sensor " << r.sensor << " read " << r.value << endl;
cout << "file size: " << sizeof(data) << " bytes" << endl;
return 0;
}sensor 3 read 19.75 file size: 48 bytes
seekg / tellg move and report the get (read) position; seekp / tellp do the same for the put (write) position.
Test yourself
4 questions · pick an answer to check it instantly
- 1
Which class do you use to read from a file?
ifstreamis an input file stream. - 2
How do you open
log.txtso new writes are added at the end?ios::appappends; the default for ofstream truncates. - 3
What does
while (getline(in, line))stop on?getlinereturns the stream, which converts to false when reading fails. - 4
Why is it often unnecessary to call
close()explicitly on file streams?File streams follow RAII.