File Handling in C++
File handling allows programs to store data permanently on disk and read it back later. Unlike variables (which are lost when the program ends), files persist after the program closes. C++ provides the <fstream> library for file operations.
File Stream Classes
| Class | Purpose |
|---|---|
ofstream | Write to files (output file stream) |
ifstream | Read from files (input file stream) |
fstream | Both read and write |
Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("notes.txt"); // create/open file for writing
if (outFile.is_open()) {
outFile << "Hello, File!" << endl;
outFile << "C++ File Handling is easy." << endl;
outFile.close();
cout << "Data written successfully." << endl;
} else {
cout << "Failed to open file." << endl;
}
return 0;
}
Output (on screen):
Data written successfully.After running, a file named notes.txt is created containing:
Hello, File!
C++ File Handling is easy.Reading from a File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("notes.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Cannot open file." << endl;
}
return 0;
}
Output:
Hello, File!
C++ File Handling is easy.Appending to a File
Opening with ios::app mode adds content to the end of an existing file without erasing it:
ofstream outFile("notes.txt", ios::app);
outFile << "New line appended." << endl;
outFile.close();
File Open Modes
| Mode | Meaning |
|---|---|
ios::in | Open for reading |
ios::out | Open for writing (creates/truncates) |
ios::app | Append to end |
ios::trunc | Erase existing content when opening |
ios::binary | Open in binary mode |
ios::ate | Move to end of file on open |
Reading and Writing with fstream
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Write
fstream file("data.txt", ios::out);
file << "Name: Alice
Age: 22
";
file.close();
// Read
file.open("data.txt", ios::in);
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
return 0;
}
Output:
Name: Alice
Age: 22Checking if File Exists
ifstream f("test.txt");
if (f.good()) {
cout << "File exists." << endl;
} else {
cout << "File not found." << endl;
}
Binary File Handling
Binary mode stores data in its raw binary format (not human-readable), useful for storing complex data structures:
struct Student {
char name[20];
int age;
float marks;
};
// Write binary
Student s = {"Vikram", 21, 85.5};
ofstream out("student.dat", ios::binary);
out.write((char*)&s, sizeof(s));
out.close();
// Read binary
Student s2;
ifstream in("student.dat", ios::binary);
in.read((char*)&s2, sizeof(s2));
in.close();
cout << s2.name << " " << s2.age << " " << s2.marks << endl;
Output:
Vikram 21 85.5File Position — seekg and seekp
seekg(pos)— Move the read pointer to positionpos.seekp(pos)— Move the write pointer to positionpos.tellg()— Returns the current read position.tellp()— Returns the current write position.
Key Takeaways
- File handling allows permanent storage and retrieval of data.
- Use
ofstreamto write,ifstreamto read, andfstreamfor both. - Always check if a file opened successfully before reading or writing.
- Use
ios::appto append without overwriting existing content. - Binary mode stores raw data and is faster for structured data like structs.
