Search⌘ K
AI Features

Binary Files

Explore the fundamentals of binary file I/O in C++, including writing and reading raw data and serializing plain-old-data structures. Understand how to handle data precisely without text conversion to build efficient, high-performance applications like game saves or image processors.

When we write to a text file, the computer performs a translation behind the scenes. It converts the number 255 into three separate characters ('2', '5', '5') and often modifies special characters like new lines and tabs to match the operating system's requirements. While this is great for human readability, it is slow and inefficient for machines.

If we are building a high-performance game save system, a database, or an image processor, we wouldn't want translation; instead, dump the exact contents of our program’s memory directly to the disk. By learning binary files, we gain the ability to save complex data structures instantly and with byte-perfect precision.

Text vs. binary files

Conceptually, all files are just sequences of bytes. The difference lies in how we interpret those bytes and how the operating system handles them during Input/Output (I/O) operations.

  • Text files: These are designed for human readability. Data is converted into character sequences (ASCII or UTF-8). For example, the integer 12345 takes up 5 bytes of storage (one for each digit). Additionally, operating systems may automatically translate special characters. For example, on Windows, a newline \n (byte 10) is often saved as \r\n (bytes 13 and 10).

  • Binary files: These store the exact raw bit patterns from memory. An int (usually 4 bytes) takes up exactly 4 bytes on disk, regardless of whether the value is 1 or 1,000,000. No character conversion or newline translation occurs. ...

Opening a binary file