📌 What is Binary File I/O in C++?
Unlike text files (where numbers like 12345 are converted to character strings like "12345" and newlines are translated), **binary files** store raw memory byte representations directly on disk. This offers immense performance and space-saving advantages for high-speed caching, image storage, and database records. In C++, binary file streaming is performed using std::ios::binary combined with the raw memory manipulation functions write() and read(), which accept pointers cast to char* along with byte-size counts (sizeof()).
std::ios::out | std::ios::binary. The write() function expects a pointer to the data cast to const char* and the exact byte length computed via sizeof().
#include
#include
int main() {
// Open file in binary output mode
std::ofstream binOut("data.bin", std::ios::out | std::ios::binary);
if (!binOut.is_open()) {
std::cerr << "Error: Failed to open binary file for writing!\n";
return 1;
}
int idCode = 90210;
double piValue = 3.1415926535;
// Write raw memory bytes of variables into the file
binOut.write(reinterpret_cast(&idCode), sizeof(idCode));
binOut.write(reinterpret_cast(&piValue), sizeof(piValue));
binOut.close();
std::cout << "Raw binary bytes written successfully to data.bin\n";
return 0;
}
std::ios::in | std::ios::binary and invoke read() passing a target memory buffer cast to char* and byte length.
#include
#include
int main() {
std::ifstream binIn("data.bin", std::ios::in | std::ios::binary);
if (!binIn.is_open()) {
std::cerr << "Error: Failed to open binary file for reading!\n";
return 1;
}
int idCode = 0;
double piValue = 0.0;
// Read raw bytes back into variable memory addresses
binIn.read(reinterpret_cast(&idCode), sizeof(idCode));
binIn.read(reinterpret_cast(&piValue), sizeof(piValue));
binIn.close();
std::cout << "Successfully deserialized binary data:\n";
std::cout << " ID Code : " << idCode << "\n";
std::cout << " Pi Value: " << piValue << "\n";
return 0;
}
#include
#include
struct PlayerRecord {
int id;
char username[32]; // Fixed-size char array for safe direct binary layout
double score;
};
int main() {
PlayerRecord p1 = {101, "CyberKnight", 9850.75};
// 1. Serialize struct to disk
{
std::ofstream out("player.dat", std::ios::binary);
out.write(reinterpret_cast(&p1), sizeof(PlayerRecord));
}
// 2. Deserialize struct from disk into new object
PlayerRecord p2;
{
std::ifstream in("player.dat", std::ios::binary);
in.read(reinterpret_cast(&p2), sizeof(PlayerRecord));
}
std::cout << "Deserialized Player Record:\n";
std::cout << " ID : " << p2.id << "\n";
std::cout << " Username: " << p2.username << "\n";
std::cout << " Score : " << p2.score << "\n";
return 0;
}
seekg().
#include
#include
#include
struct Employee {
int empId;
char name[50];
double salary;
};
void addEmployee(int id, const char* name, double sal) {
std::ofstream db("employees.db", std::ios::out | std::ios::binary | std::ios::app);
Employee emp;
emp.empId = id;
std::strncpy(emp.name, name, sizeof(emp.name));
emp.salary = sal;
db.write(reinterpret_cast(&emp), sizeof(Employee));
}
void readEmployeeRecord(int recordIndex) {
std::ifstream db("employees.db", std::ios::in | std::ios::binary);
db.seekg(recordIndex * sizeof(Employee), std::ios::beg);
Employee emp;
if (db.read(reinterpret_cast(&emp), sizeof(Employee))) {
std::cout << "Record [" << recordIndex << "] -> ID: " << emp.empId
<< " | Name: " << emp.name
<< " | Salary: $" << emp.salary << "\n";
} else {
std::cerr << "Record index out of bounds!\n";
}
}
int main() {
std::cout << "============================================\n";
std::cout << "🗄️ BINARY EMPLOYEE DATABASE DEMO\n";
std::cout << "============================================\n";
// Add multiple records
addEmployee(1, "Alice Smith", 85000.0);
addEmployee(2, "Bob Johnson", 92000.0);
addEmployee(3, "Charlie Davis", 78000.0);
// Random access read: Fetch record index 1 directly without scanning records 0
readEmployeeRecord(1);
std::cout << "============================================\n";
return 0;
}
C++ TEXT VS BINARY FILE ARCHITECTURE MATRIX:
┌───────────────────────────┬───────────────────────────────┬──────────────────────────────────────────────────────────┐
│ Feature / Attribute │ Text Files (`std::ios::out`) │ Binary Files (`std::ios::binary`) │
├───────────────────────────┼───────────────────────────────┼──────────────────────────────────────────────────────────┤
│ Data Representation │ Formatted human-readable text │ Raw machine memory bytes (exact bit pattern) │
│ Newline Translation │ Converts `\n` to `\r\n` (Win) │ No translation; exact byte preservation │
│ Performance │ Slower (requires formatting) │ Extremely fast (direct memory dumping) │
│ File Size │ Larger for numeric data │ Compact and fixed-size (especially for structs) │
│ Human Readability │ Viewable in any text editor │ Requires hex editor or custom deserializer │
├───────────────────────────┴───────────────────────────────┴──────────────────────────────────────────────────────────┤
│ ENGINEERING BEST PRACTICES: │
│ 1. Always pass `std::ios::binary` when opening streams for binary operations to disable platform newline conversions.│
│ 2. Avoid serializing structs containing raw pointers (`std::string`, raw pointers) directly; use fixed arrays or │
│ serialization libraries (Protocol Buffers, FlatBuffers, JSON) for complex pointer-based object graphs. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘