C++ File Handling — ofstream, ifstream, fstream | Tutorials Logic
File Streams in C++
C++ uses stream classes from <fstream> for file I/O:
| Class | Purpose |
|---|---|
ofstream | Write to file (output file stream) |
ifstream | Read from file (input file stream) |
fstream | Read and write (both directions) |
| Mode Flag | Description |
|---|---|
ios::in | Open for reading |
ios::out | Open for writing (truncates existing) |
ios::app | Append to end of file |
ios::binary | Binary mode |
ios::trunc | Truncate file to zero length |
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Write to file
ofstream outFile("data.txt");
if (!outFile.is_open()) {
cerr << "Failed to open file!" << endl;
return 1;
}
outFile << "Line 1: Hello, C++ File I/O!" << endl;
outFile << "Line 2: Writing to a file." << endl;
outFile << "Line 3: Done." << endl;
outFile.close();
cout << "File written successfully." << endl;
// Append to file
ofstream appendFile("data.txt", ios::app);
appendFile << "Line 4: Appended line." << endl;
appendFile.close();
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("data.txt");
if (!inFile.is_open()) {
cerr << "Cannot open file!" << endl;
return 1;
}
// Read line by line
string line;
int lineNum = 1;
while (getline(inFile, line)) {
cout << lineNum++ << ": " << line << endl;
}
inFile.close();
// Read word by word
ifstream wordFile("data.txt");
string word;
int wordCount = 0;
while (wordFile >> word) wordCount++;
cout << "Word count: " << wordCount << endl;
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
char name[50];
int age;
double gpa;
};
int main() {
// Write binary
Student s1 = {"Alice", 20, 3.8};
Student s2 = {"Bob", 22, 3.5};
ofstream out("students.bin", ios::binary);
out.write(reinterpret_cast<char*>(&s1), sizeof(Student));
out.write(reinterpret_cast<char*>(&s2), sizeof(Student));
out.close();
// Read binary
ifstream in("students.bin", ios::binary);
Student s;
while (in.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
cout << s.name << " | Age: " << s.age << " | GPA: " << s.gpa << endl;
}
in.close();
// fstream - read and write
fstream rw("data.txt", ios::in | ios::out);
rw.seekg(0, ios::end); // seek to end
long size = rw.tellg(); // get file size
cout << "File size: " << size << " bytes" << endl;
rw.close();
return 0;
}
Level Up Your C plus plus Skills
Master C plus plus with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related C++ Topics