Binary File Operations in C++
Read and write binary files in C++: save structs with write() and sizeof, load them with read(), and learn why std::string cannot be written this way.
1#include <iostream>2#include <fstream>3using namespace std;45struct Student {6 int id;7 char name[50];8 float marks;9};1011int main() {12 // Write binary data13 ofstream outFile("students.dat", ios::binary);1415 if (outFile.is_open()) {16 Student s1 = {101, "Alice", 95.5};17 Student s2 = {102, "Bob", 87.0};18 Student s3 = {103, "Charlie", 92.5};1920 // Write structures to binary file21 outFile.write((char*)&s1, sizeof(Student));22 outFile.write((char*)&s2, sizeof(Student));23 outFile.write((char*)&s3, sizeof(Student));2425 outFile.close();26 cout << "Binary data written successfully!" << endl;27 }2829 // Read binary data30 ifstream inFile("students.dat", ios::binary);3132 if (inFile.is_open()) {33 Student s;34 cout << "\nReading binary data:" << endl;3536 while (inFile.read((char*)&s, sizeof(Student))) {37 cout << "ID: " << s.id << ", Name: " << s.name38 << ", Marks: " << s.marks << endl;39 }4041 inFile.close();42 }4344 return 0;45}
Sample Output
ID: 102, Name: Bob, Marks: 87
87.0f prints without the trailing zero.
In this one
- How text and binary files differ
- How write() and read() copy raw bytes
- Why the struct uses char[50] instead of string
- Why binary files are not portable
How it works
- 1
Define Student with id, name[50], and marks.
- 2
Open students.dat with ios::binary.
- 3
write each struct's bytes with sizeof(Student).
- 4
Reopen with ifstream and ios::binary.
- 5
read one record per loop and print it.
Edge cases
Using std::string in the struct
Change name to string.
The file stores the string's internal pointer. Reading it back gives a dangling pointer and undefined behavior. Use a fixed char array or write the length and characters separately.
Truncated file
Cut the last 10 bytes off students.dat.
The last read gets fewer than sizeof(Student) bytes, so the loop ends after two records.
Name longer than 49 characters
Initialize name with a 60-character literal.
It does not compile, because the literal does not fit in char[50]. Copying longer text at runtime would overflow the array.
What's going on
Text files store values as readable characters. Binary files store the raw bytes that are in memory. This program writes three Student structs straight to students.dat and reads them back.
Student has an int id, a char name[50], and a float marks. A fixed-size char array is used on purpose: a std::string holds a pointer to heap memory, and writing a pointer to a file is useless because the address means nothing when you read it later.
ofstream outFile("students.dat", ios::binary); opens the file in binary mode. On Windows this stops the library from turning `
bytes into
`; on Linux and macOS there is no difference, but it states the intent.
outFile.write((char*)&s1, sizeof(Student)); writes the struct's bytes. write wants a const char* and a byte count, so the address of s1 is cast to char* and the size comes from sizeof. Each record is the same size, typically 60 bytes: 4 for id, 50 for name, 2 bytes of padding so marks lines up on a 4-byte boundary, and 4 for marks. The file ends up 180 bytes.
The reader opens with ios::binary too and loops on inFile.read((char*)&s, sizeof(Student)). read fills s with the next record's bytes, and the stream turns false when fewer than a full record remain, ending the loop after three students.
Marks print as 95.5, 87, and 92.5. cout does not show trailing zeros, so 87.0 prints as 87.
Binary files are fast and compact, but they are not portable. A file written on one compiler or CPU might not read correctly on another if the padding, the size of int, or the byte order differ. For data shared between systems, use text, CSV, or JSON instead.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ofstream, ifstream). Leave one out and the compiler stops at the first name it does not recognize.
Understanding Binary Files
Binary File Concept:
vs Text Files:
Opening Binary File
Using ios::binary:
ofstream outFile("students.dat", ios::binary);
ifstream inFile("students.dat", ios::binary);
What happens here:
Writing Binary Data
Using write():
Student s1 = {101, "Alice", 95.5};
outFile.write((char*)&s1, sizeof(Student));
What happens here:
Syntax:
write((char*)&object, sizeof(objectType))
Reading Binary Data
Using read():
Student s;
inFile.read((char*)&s, sizeof(Student));
What happens here:
Loop Reading:
while (inFile.read((char*)&s, sizeof(Student))) {
// Process each structure
}
When to Use Binary Files
Good fits:
Example Scenarios:
Important Considerations
Data Structure:
Portability:
Size Efficiency:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is name a char[50] and not a string?
Pick an answer to check it.
Question 2
When does the read loop stop?
Pick an answer to check it.
Questions people ask
How do I jump to record n?
inFile.seekg(n * sizeof(Student)); then read once.
Why cast to char*?
read and write work with bytes, and char is one byte.
Can I open students.dat in a text editor?
You will see the names and some garbage characters, since the numbers are raw bytes.