Date:

Binary File Handling in C++: A Beginner’s Guide

Binary File Handling in C++

Introduction

Binary file handling in C++ is a powerful technique that allows us to store and retrieve data efficiently. Unlike text files, which store data as human-readable characters, binary files store raw data in a format that is directly understood by the computer. This makes them faster and more suitable for handling structured data such as objects, arrays, and large datasets.

Why Use Binary Files?

Binary files offer several advantages over text files:

  • Faster reading and writing operations
  • No conversion is needed between data types and text
  • Suitable for storing complex data like images, videos, and database records

File Handling in C++

C++ provides the <fstream> library for file handling. It contains three important classes:

  • ifstream: For reading files
  • ofstream: For writing files
  • fstream: For both reading and writing

Writing to a Binary File

To write to a binary file, we use the write() function to store data in a file.

Example: Writing a Single Record to a Binary File

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s = {"John", 20, 85.5};

    ofstream file("student.dat", ios::binary);
    file.write((char*)&s, sizeof(s));
    file.close();

    cout << "Data saved successfully!" << endl;
    return 0;
}

Reading from a Binary File

To read from a binary file, we use the read() function to retrieve stored data.

Example: Reading a Record from a Binary File

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s;

    ifstream file("student.dat", ios::binary);
    file.read((char*)&s, sizeof(s));
    file.close();

    cout << "Name: " << s.name << "\nAge: " << s.age << "\nMarks: " << s.marks << endl;
    return 0;
}

Appending Data to a Binary File

To add new data without overwriting existing records, we use append mode (ios::app).

Example: Appending Data

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s = {"Alice", 21, 90.2};

    ofstream file("student.dat", ios::binary | ios::app);
    file.write((char*)&s, sizeof(s));
    file.close();

    cout << "Data appended successfully!" << endl;
    return 0;
}

Searching for a Record in a Binary File

To search for a record, we loop through all entries and compare names using strcmp().

Example: Searching for a Record

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s;
    char searchName[30];

    cout << "Enter name to search: ";
    cin >> searchName;

    ifstream file("student.dat", ios::binary);
    bool found = false;

    while (file.read((char*)&s, sizeof(s))) {
        if (strcmp(s.name, searchName) == 0) {
            cout << "Record Found!\n";
            cout << "Name: " << s.name << "\nAge: " << s.age << "\nMarks: " << s.marks << endl;
            found = true;
            break;
        }
    }

    if (!found) cout << "Record not found!" << endl;
    file.close();
    return 0;
}

Modifying a Record in a Binary File

To modify a record, we:

  1. Read the file
  2. Find the record to modify
  3. Update the data and rewrite it

Example: Modifying Marks of a Student

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s;
    char searchName[30];

    cout << "Enter name to modify: ";
    cin >> searchName;

    ifstream file("student.dat", ios::binary | ios::in | ios::out);

    while (file.read((char*)&s, sizeof(s))) {
        if (strcmp(s.name, searchName) == 0) {
            cout << "Enter new marks: ";
            cin >> s.marks;

            file.seekp(-sizeof(s), ios::cur);
            file.write((char*)&s, sizeof(s));

            cout << "Record updated successfully!" << endl;
            break;
        }
    }

    file.close();
    return 0;
}

Deleting a Record from a Binary File

To delete a record:

  1. Copy all records except the one to delete into a new file
  2. Replace the old file with the new file

Example: Deleting a Record

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Student {
    char name[30];
    int age;
    float marks;
};

int main() {
    Student s;
    char deleteName[30];

    cout << "Enter name to delete: ";
    cin >> deleteName;

    ifstream file("student.dat", ios::binary);
    ofstream temp("temp.dat", ios::binary);

    while (file.read((char*)&s, sizeof(s))) {
        if (strcmp(s.name, deleteName) != 0) {
            temp.write((char*)&s, sizeof(s));
        }
    }

    file.close();
    temp.close();

    remove("student.dat");
    rename("temp.dat", "student.dat");

    cout << "Record deleted successfully!" << endl;
    return 0;
}

Conclusion

Binary file handling in C++ is essential for efficient data storage and retrieval. We covered:

  • Writing and reading binary files
  • Appending new records
  • Searching, modifying, and deleting records

Understanding these concepts will help you efficiently manage structured data in real-world applications. Happy coding!

FAQs

Q: Why use binary files?
A: Binary files offer faster reading and writing operations, no conversion is needed between data types and text, and are suitable for storing complex data like images, videos, and database records.

Q: What are the three important classes in C++’s <fstream> library?
A: ifstream, ofstream, and fstream

Q: How do you write to a binary file?
A: Use the write() function to store data in a file.

Q: How do you read from a binary file?
A: Use the read() function to retrieve stored data.

Q: How do you append new data to a binary file?
A: Use append mode (ios::app) when opening the file.

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here