File Handling · intermediate · ~8 min

Binary files

Read/write structured binary data correctly.

Lesson

Binary files store raw bytes — no \n translation, no encoding. Open with "rb" / "wb". Typical use: serialise a struct with fwrite(&obj, sizeof obj, 1, f).

Two portability traps: endianness (byte order varies across machines) and padding (structs may include hidden bytes between fields). For data exchanged across systems, prefer explicit byte-by-byte serialisation.

Common mistakes

  • Writing fwrite(&struct, sizeof struct, 1, f) and expecting another platform to read it correctly — endianness and padding break that.