C++ File Handling – Read, Write, and Manage Files in C++
File handling is essential in C++ for storing and retrieving data between program runs. Whether saving user input or reading configuration files, C++ provides powerful file stream capabilities through the <fstream> header to work with both text and binary files.
Introduction – Why Learn File Handling in C++?
Most real-world applications need to interact with external data sources. C++ supports robust file I/O (input/output) for reading/writing files, storing binary data, and processing text documents. Mastering file handling allows you to build feature-rich, data-driven applications.
In this guide, you’ll learn:
- File stream classes in
<fstream> - How to read from and write to text and binary files
- File opening modes for fine-grained control
- Binary file operations using
.read()and.write()
Topics Covered
| Subtopic | Description |
|---|---|
C++ File Streams – <fstream> | Classes and syntax used for reading and writing files |
| C++ Reading and Writing Files | Techniques for reading/writing text and binary content |
| C++ File Modes & Binary File Operations | File opening flags and low-level binary I/O using .read()/.write() |
C++ File Streams – <fstream>
The <fstream> header provides three main classes for file I/O:
| Class | Description |
|---|---|
ifstream | Input file stream (used to read files) |
ofstream | Output file stream (used to write files) |
fstream | Input/output stream (used to read/write) |
Example:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("data.txt"); // Create and open a file for writing
outFile << "Hello, File Handling!";
outFile.close(); // Always close the file
ifstream inFile("data.txt"); // Open the file for reading
string line;
getline(inFile, line);
cout << line << endl; // Output: Hello, File Handling!
inFile.close();
return 0;
}
C++ Reading and Writing Files
Reading from a file:
ifstream file("sample.txt");
string word;
while (file >> word) {
cout << word << endl;
}
file.close();
Writing to a file:
ofstream file("output.txt");
file << "C++ File Handling\n";
file.close();
Text Mode vs. Binary Mode:
- Text Mode: Default mode, reads/writes human-readable data
- Binary Mode: Handles raw bytes (suitable for structures, images)
C++ File Modes & Binary File Operations
You can open files in various modes using flags from the ios namespace:
| Mode | Purpose |
|---|---|
ios::in | Open file for reading |
ios::out | Open file for writing (overwrites if exists) |
ios::app | Append to the end of file |
ios::ate | Move to end immediately after opening |
ios::binary | Open file in binary mode |
ios::trunc | Truncate file when opening with ios::out |
Binary File Example (Write/Read Structure):
#include <fstream>
#include <iostream>
using namespace std;
struct Employee {
int id;
char name[20];
};
int main() {
Employee e1 = {101, "Alice"};
// Write to binary file
ofstream out("emp.dat", ios::binary);
out.write((char*)&e1, sizeof(e1));
out.close();
// Read from binary file
Employee e2;
ifstream in("emp.dat", ios::binary);
in.read((char*)&e2, sizeof(e2));
in.close();
cout << "ID: " << e2.id << ", Name: " << e2.name << endl; // Output: ID: 101, Name: Alice
return 0;
}
Why Use Binary Files?
- Efficient storage of complex data structures
- More compact than text
- Better performance for large datasets
Summary – Recap & Next Steps
C++ provides powerful tools for reading, writing, and managing files using text and binary formats. By understanding streams, file modes, and binary I/O, you can store structured data efficiently and enable persistent storage in your applications.
Key Takeaways:
- Use
<fstream>,<ifstream>, and<ofstream>for file I/O - Always open files with appropriate
iosmodes - Use
.read()and.write()for raw binary operations - Remember to
.close()all files after operations
Real-World Relevance:
- Storing user preferences, logs, and records
- Reading configuration or report files
- Managing structured binary formats like databases, media files
Frequently Asked Questions (FAQs)
What is the difference between ofstream and fstream?
ofstream is for output-only (writing), while fstream supports both input and output operations on files.
Can I open a file in both read and write mode?
Yes, use fstream with ios::in | ios::out to enable both operations.
What happens if a file does not exist during read?
The stream fails to open, and you should check ifstream.fail() to avoid undefined behavior.
Why use binary mode over text mode?
Binary mode is more efficient and suitable for saving structured data (e.g., structs, images), whereas text mode is easier for human interaction.
What does .write((char*)&obj, sizeof(obj)) do?
It writes raw bytes of obj to a binary file. Use only for Plain Old Data (POD) types like structs.
Share Now :
