Module 21: File Handling in C++
File handling allows a C++ program to store data permanently in files and retrieve it later. Unlike variables stored in memory, file data remains available even after the program ends.
C++ provides the <fstream> library for working with files.
There are three main file stream classes:
ifstream– Read data from files.ofstream– Write data to files.fstream– Read and write data.
1. ifstream
ifstream (Input File Stream) is used to read data from a file.
Syntax
1ifstream file("filename.txt");
Example
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 ifstream file("message.txt"); 9 10 string line; 11 12 while (getline(file, line)) 13 { 14 cout << line << endl; 15 } 16 17 file.close(); 18 19 return 0; 20}
Output
1Hello World 2Welcome to C++ File Handling
2. ofstream
ofstream (Output File Stream) is used to create and write data to a file.
Example
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 ofstream file("message.txt"); 9 10 file << "Hello World" << endl; 11 file << "Welcome to C++"; 12 13 file.close(); 14 15 return 0; 16}
After running the program, the file message.txt contains:
1Hello World 2Welcome to C++
3. fstream
fstream supports both reading and writing using the same file stream.
Example
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 fstream file("student.txt", ios::out); 9 10 file << "Ankit"; 11 12 file.close(); 13 14 file.open("student.txt", ios::in); 15 16 string name; 17 18 getline(file, name); 19 20 cout << name; 21 22 file.close(); 23 24 return 0; 25}
Output
1Ankit
4. Text Files
Text files store human-readable characters.
Examples:
.txt.csv.json.xml
Example
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 ofstream file("notes.txt"); 9 10 file << "C++ Programming Language"; 11 12 file.close(); 13 14 return 0; 15}
Contents of notes.txt
1C++ Programming Language
5. Binary Files
Binary files store data in binary format, making them more compact and efficient for certain applications.
Writing Binary Data
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 int number = 100; 9 10 ofstream file("data.bin", ios::binary); 11 12 file.write(reinterpret_cast<char*>(&number), sizeof(number)); 13 14 file.close(); 15 16 return 0; 17}
Reading Binary Data
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 int number; 9 10 ifstream file("data.bin", ios::binary); 11 12 file.read(reinterpret_cast<char*>(&number), sizeof(number)); 13 14 cout << number; 15 16 file.close(); 17 18 return 0; 19}
Output
1100
6. CSV Files
CSV (Comma-Separated Values) files store tabular data.
Example students.csv
1Name,Age,Marks 2Ankit,22,90 3Rahul,21,88
Writing CSV
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 ofstream file("students.csv"); 9 10 file << "Name,Age,Marks\n"; 11 file << "Ankit,22,90\n"; 12 file << "Rahul,21,88"; 13 14 file.close(); 15 16 return 0; 17}
Reading CSV
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6int main() 7{ 8 ifstream file("students.csv"); 9 10 string line; 11 12 while (getline(file, line)) 13 { 14 cout << line << endl; 15 } 16 17 file.close(); 18 19 return 0; 20}
7. Serialization Basics
Serialization is the process of converting an object's data into a format that can be stored or transmitted and later reconstructed.
For beginners, serialization can be implemented by writing object data to a file.
Example
1#include <iostream> 2#include <fstream> 3 4using namespace std; 5 6class Student 7{ 8public: 9 string name; 10 int age; 11}; 12 13int main() 14{ 15 Student s; 16 17 s.name = "Ankit"; 18 s.age = 22; 19 20 ofstream file("student.txt"); 21 22 file << s.name << endl; 23 file << s.age; 24 25 file.close(); 26 27 return 0; 28}
Contents of student.txt
1Ankit 222
Note: Professional applications often use serialization libraries such as Protocol Buffers, JSON, XML, or MessagePack instead of writing fields manually.
File Open Modes
| Mode | Description |
|---|---|
ios::in | Open file for reading |
ios::out | Open file for writing |
ios::app | Append data to the end of the file |
ios::ate | Open and move to the end of the file |
ios::trunc | Remove existing file contents |
ios::binary | Open file in binary mode |
Best Practices
- Always check whether a file opened successfully.
- Close files after use.
- Use
getline()for reading complete lines. - Use binary mode for non-text data.
- Handle file errors gracefully.
- Prefer structured formats such as CSV, JSON, or XML when exchanging data.
Practice Problems
- Create a text file and write five lines into it.
- Read a text file line by line.
- Append new content to an existing file.
- Store and read integer values from a binary file.
- Create and read a CSV file containing employee records.
- Serialize and deserialize a simple
Studentobject.
Interview Questions
- What is file handling in C++?
- What is the difference between
ifstream,ofstream, andfstream? - What are text files and binary files?
- What is the purpose of
ios::binary? - How do you append data to a file?
- What is a CSV file?
- What is serialization?
- Why should you always close a file?
- How can you check whether a file opened successfully?
Summary
In this module, you learned:
- How file handling works in C++.
- How to read files using
ifstream. - How to write files using
ofstream. - How to read and write using
fstream. - The differences between text and binary files.
- How to create and process CSV files.
- The basics of serialization and persistent data storage.
- Best practices for safe and efficient file operations.
Next Module: Module 22: Templates and Generic Programming — Function Templates, Class Templates, Template Specialization, Variadic Templates, Non-Type Template Parameters, and Generic Programming.