Binary File I/O in C++
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.
Open with binary flag
std::ofstream out("a.bin", std::ios::binary); — without the flag, Windows mangles byte 0x0A on the way through.
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.
Read back symmetrically
in.read(reinterpret_cast<char*>(&x), sizeof(x)); reverses it; check gcount() after short reads near end-of-file.
Know the limits
Padding bytes, endianness, and 32-vs-64-bit sizes vary — binary files are not portable artifacts.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.