Binary File Operations
Binary File Reading and Writing in C++
IntermediateTopic: File Handling Programs
C++ Binary File Operations Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
int id;
char name[50];
float marks;
};
int main() {
// Write binary data
ofstream outFile("students.dat", ios::binary);
if (outFile.is_open()) {
Student s1 = {101, "Alice", 95.5};
Student s2 = {102, "Bob", 87.0};
Student s3 = {103, "Charlie", 92.5};
// Write structures to binary file
outFile.write((char*)&s1, sizeof(Student));
outFile.write((char*)&s2, sizeof(Student));
outFile.write((char*)&s3, sizeof(Student));
outFile.close();
cout << "Binary data written successfully!" << endl;
}
// Read binary data
ifstream inFile("students.dat", ios::binary);
if (inFile.is_open()) {
Student s;
cout << "\nReading binary data:" << endl;
while (inFile.read((char*)&s, sizeof(Student))) {
cout << "ID: " << s.id << ", Name: " << s.name
<< ", Marks: " << s.marks << endl;
}
inFile.close();
}
return 0;
}Output
Binary data written successfully! Reading binary data: ID: 101, Name: Alice, Marks: 95.5 ID: 102, Name: Bob, Marks: 87 ID: 103, Name: Charlie, Marks: 92.5
Understanding Binary File Operations
Binary file operations use ios: :binary mode flag. write() writes raw bytes, read() reads raw bytes. Use sizeof() to determine size of data structure. Binary files are more efficient for structured data and preserve exact data representation. Cast pointers to (char*) for read/write operations.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.