Work with Binary Files Using fstream
In this step, you'll learn how to work with binary files using the fstream
class in C++. Binary files store data in its raw binary format, which is different from text files and useful for storing structured data efficiently.
Create a new C++ file called binary_files.cpp
:
touch ~/project/binary_files.cpp
Add the following code to the binary_files.cpp
file:
#include <iostream>
#include <fstream>
#include <string>
// Simple struct to demonstrate binary file writing
struct Student {
int id;
char name[50];
double gpa;
};
void writeBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::out | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for writing!" << std::endl;
return;
}
// Create some student records
Student students[3] = {
{1, "John Doe", 3.5},
{2, "Alice Smith", 3.8},
{3, "Bob Johnson", 3.2}
};
// Write entire struct to binary file
binaryFile.write(reinterpret_cast<char*>(students), sizeof(students));
binaryFile.close();
std::cout << "Binary file written successfully!" << std::endl;
}
void readBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::in | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for reading!" << std::endl;
return;
}
Student students[3];
// Read entire struct from binary file
binaryFile.read(reinterpret_cast<char*>(students), sizeof(students));
std::cout << "Student Records:" << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << "ID: " << students[i].id
<< ", Name: " << students[i].name
<< ", GPA: " << students[i].gpa << std::endl;
}
binaryFile.close();
}
int main() {
// Write binary file
writeBinaryFile();
// Read binary file
readBinaryFile();
return 0;
}
Compile the program:
g++ binary_files.cpp -o binary_files
Run the executable:
./binary_files
Example output:
Binary file written successfully!
Student Records:
ID: 1, Name: John Doe, GPA: 3.5
ID: 2, Name: Alice Smith, GPA: 3.8
ID: 3, Name: Bob Johnson, GPA: 3.2
Key points about binary files:
- Use
std::ios::binary
flag for binary mode
write()
and read()
methods for binary data
reinterpret_cast
used to convert between types
- Useful for storing structured data efficiently
- Preserves exact binary representation of data
You can think of binary files like a precise blueprint. They store data exactly as it exists in memory, without any text conversion.