Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateFile Handling ProgramsExample 4 of 6
binary-file-operations.cpp
1#include <iostream>
2#include <fstream>
3using namespace std;
4
5struct Student {
6 int id;
7 char name[50];
8 float marks;
9};
10
11int main() {
12 // Write binary data
13 ofstream outFile("students.dat", ios::binary);
14
15 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};
19
20 // Write structures to binary file
21 outFile.write((char*)&s1, sizeof(Student));
22 outFile.write((char*)&s2, sizeof(Student));
23 outFile.write((char*)&s3, sizeof(Student));
24
25 outFile.close();
26 cout << "Binary data written successfully!" << endl;
27 }
28
29 // Read binary data
30 ifstream inFile("students.dat", ios::binary);
31
32 if (inFile.is_open()) {
33 Student s;
34 cout << "\nReading binary data:" << endl;
35
36 while (inFile.read((char*)&s, sizeof(Student))) {
37 cout << "ID: " << s.id << ", Name: " << s.name
38 << ", Marks: " << s.marks << endl;
39 }
40
41 inFile.close();
42 }
43
44 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. 1

    Define Student with id, name[50], and marks.

  2. 2

    Open students.dat with ios::binary.

  3. 3

    write each struct's bytes with sizeof(Student).

  4. 4

    Reopen with ifstream and ios::binary.

  5. 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:

Stores data as raw bytes
No text conversion
Preserves exact representation
More efficient for structured data

vs Text Files:

Text: human-readable, larger size
Binary: machine-readable, smaller size
Binary: faster read/write
Binary: exact data preservation

Opening Binary File

Using ios::binary:

ofstream outFile("students.dat", ios::binary);

ifstream inFile("students.dat", ios::binary);

What happens here:

ios::binary: binary mode flag
No text conversion
Raw byte operations
Efficient for structures

Writing Binary Data

Using write():

Student s1 = {101, "Alice", 95.5};

outFile.write((char*)&s1, sizeof(Student));

What happens here:

write(): writes raw bytes
(char*)&s1: cast structure pointer to char*
sizeof(Student): number of bytes to write
Writes entire structure as bytes

Syntax:

write((char*)&object, sizeof(objectType))

Reading Binary Data

Using read():

Student s;

inFile.read((char*)&s, sizeof(Student));

What happens here:

read(): reads raw bytes
(char*)&s: cast structure pointer to char*
sizeof(Student): number of bytes to read
Reads entire structure from bytes

Loop Reading:

while (inFile.read((char*)&s, sizeof(Student))) {

// Process each structure

}

When to Use Binary Files

Good fits:

Structured data (structures, arrays)
Large datasets
Performance-critical I/O
Exact data preservation
Database-like storage

Example Scenarios:

Student records
Image data
Database files
Game save files
Performance-critical applications

Important Considerations

Data Structure:

Must match exactly when reading
Same structure definition
Same member order
Same data types

Portability:

Binary files may not be portable
Different systems (endianness)
Platform-dependent
Use text for portability

Size Efficiency:

Binary: smaller file size
No text conversion overhead
Faster read/write
More efficient for large data

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.