C++ Tutorial
Estimated reading: 4 minutes 52 views

๐Ÿ“‚ 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

SubtopicDescription
๐Ÿ“˜ C++ File Streams โ€“ <fstream>Classes and syntax used for reading and writing files
๐Ÿ“– C++ Reading and Writing FilesTechniques for reading/writing text and binary content
๐Ÿ’พ C++ File Modes & Binary File OperationsFile 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:

ClassDescription
ifstreamInput file stream (used to read files)
ofstreamOutput file stream (used to write files)
fstreamInput/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:

ModePurpose
ios::inOpen file for reading
ios::outOpen file for writing (overwrites if exists)
ios::appAppend to the end of file
ios::ateMove to end immediately after opening
ios::binaryOpen file in binary mode
ios::truncTruncate 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 ios modes
  • 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ“‚ C++ File Handling

Or Copy Link

CONTENTS
Scroll to Top