Learn C++
#include "ioformatting/binary_io.hpp"

Binary File I/O in C++

//concept

Text mode translates newlines per platform; binary mode (std::ios::binary) disables all translation so bytes pass through exactly — mandatory for images, archives, and serialized structs. Binary I/O works in raw chunks: write() dumps memory as-is, read() pulls it back, and gcount() reports how many bytes the last read actually got.

The danger is portability: padding, endianness, and type sizes differ across machines, so binary dumps are for same-machine checkpoints and performance, never for exchange formats — use text or a real serialization format for those.

//how it works
1

Open with binary flag

std::ofstream out("a.bin", std::ios::binary); — without the flag, Windows mangles byte 0x0A on the way through.

2

Write raw memory

out.write(reinterpret_cast<const char*>(&x), sizeof(x)); dumps an object's exact bytes — fast, but format-locked to this build.

3

Read back symmetrically

in.read(reinterpret_cast<char*>(&x), sizeof(x)); reverses it; check gcount() after short reads near end-of-file.

4

Know the limits

Padding bytes, endianness, and 32-vs-64-bit sizes vary — binary files are not portable artifacts.

//example
#include <iostream>
#include <fstream>
 
int main() {
int values[3]{10, 20, 30};
std::ofstream out("nums.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(values), sizeof(values));
out.close();
int back[3]{};
std::ifstream in("nums.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(back), sizeof(back));
std::cout << back[0] << ", " << back[1] << ", " << back[2] << std::endl;
return 0;
}
Output
10, 20, 30
1The array's 12 bytes dump verbatim into nums.bin — no formatting, no newlines, no translation.
2Reading the same 12 bytes back into a fresh array reconstructs the values bit-for-bit.
310, 20, 30 prints — the round trip preserved every value exactly.
//use cases
Checkpointing simulation state for same-machine resume
Dumping sensor and audio buffers where text conversion would bloat
Reading fixed-layout binary formats (BMP headers, replay files)
Choosing text/JSON/protobuf instead whenever files cross machines

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.