⚡C++IntermediateLesson 30 of 50CamboFreelanceJune 19, 2026
C++ Files
Learn C++ file I/O with fstream, ofstream, and ifstream. Read, write, and append files with error checking.
Intermediate8 min readLesson 30 of 50
File I/O with fstream
C++ uses the <fstream> header for file operations. Three classes:
Class
Purpose
ofstream
Write to files (output file stream)
ifstream
Read from files (input file stream)
fstream
Read and write
Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("students.txt"); // creates or overwrites
if (!file) {
cerr << "Cannot open file!" << endl;
return 1;
}
file << "Alice, 95" << endl;
file << "Bob, 82" << endl;
file << "Carol, 78" << endl;
file.close();
cout << "File written successfully." << endl;
return 0;
}
Reading from a File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("students.txt");
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
return 0;
}
Output:
Alice, 95
Bob, 82
Carol, 78
Append Mode
ofstream file("log.txt", ios::app); // append without erasing
file << "New log entry" << endl;
file.close();
Exercise
Write a program that: (1) writes 5 numbers (1–5) to a file, one per line. (2) Reads them back and prints their sum.
Show Solution
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Write
ofstream out("numbers.txt");
for (int i = 1; i <= 5; i++) out << i << endl;
out.close();
// Read and sum
ifstream in("numbers.txt");
int n, sum = 0;
while (in >> n) sum += n;
in.close();
cout << "Sum: " << sum << endl; // 15
return 0;
}
Quiz
Which class is used to write to a file in C++?
A) ifstream
B) fileout
C) ofstream
D) writefile
Answer
C) ofstream
Which flag opens a file in append mode?
A) ios::in
B> ios::append
C) ios::app
D) ios::add
Answer
C) ios::app
Summary
#include <fstream> for file I/O.
ofstream writes; ifstream reads; fstream does both.
Always check if the file opened and close it when done.
Use ios::app to append without erasing existing content.