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.
In this article, we will explore the basics of binary file handling in C++, including how to read, write, append, search, modify, and delete records in a binary file.
1. 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.
2. 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.
To work with binary files, we use ios::binary
mode when opening a file.
We use the .write()
function to store data in a binary 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;
}
✔ We define a structure Student
to store student details.
✔ The file is opened in binary write mode using ios::binary
.
✔ .write()
saves the entire Student
object to the file.
✔ Finally, we close the file.
4. Reading Data 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;
}
✔ The file is opened in binary read mode.
✔ .read()
retrieves the stored object and loads it into memory.
✔ We then display the retrieved information.
5. 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;
}
✔ The file is opened in an append mode.
✔ New data is added without deleting previous records.
6. Searching for a Record in a Binary File
We can search for a specific record by reading each entry one by one.
Example: Searching for a Student by Name
#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;
}
✔ We loop through all records and compare names using strcmp()
.
✔ If a match is found, the details are displayed.
7. Modifying a Record in a Binary File
To modify a record, we:
Read the file.
Find the record to modify.
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];
fstream file("student.dat", ios::binary | ios::in | ios::out);
cout << "Enter name to modify: ";
cin >> searchName;
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;
}
✔ We open the file in both read and write mode.
✔ The .seekp()
function moves the file pointer back to update the record in place.
8. Deleting a Record from a Binary File
To delete a record:
Copy all records except the one to be deleted into a new file.
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;
}
✔ We use a temporary file to store all records except the one to delete.
✔ The old file is removed and replaced with the new file.
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!
Also you can check all the above cpp codes on my GitHub repo... ;)
https://github.com/AlenBluBerry/Binary-File-Handling/tree/main/Cpp%20codes
Top comments (0)