๐ 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 :
