Binary I/O
Text files hold human-readable characters. Binary files dump raw bytes straight to disk — whatever your data looks like in memory is what lands in the file. Faster and tighter on disk, but you can't cat the result and learn anything.
Reading and Writing Binary Data
FILE *fp = fopen("data.bin", "wb"); // note the 'b'
int numbers[] = {1, 2, 3, 4, 5};fwrite(numbers, sizeof(int), 5, fp);fclose(fp);fwrite writes 5 elements of size sizeof(int) from the numbers array.
Reading Binary Data
FILE *fp = fopen("data.bin", "rb");int buffer[5];size_t read = fread(buffer, sizeof(int), 5, fp);printf("Read %zu elements\n", read);fclose(fp);fread returns the count of elements it actually read. That number may fall short of what you asked for if the file ends early or something errors mid-read.
Binary files are not portable between systems with different byte orders (endianness), type sizes or struct layouts. An int is 4 bytes on both x86-64 and a big-endian PowerPC, yet the value 1 written by the first reads back as 16,777,216 on the second, because the bytes come out in the opposite order. For portable formats, use text or define an explicit binary format with fixed-size fields and a stated byte order.
Seeking
You can jump to any position in a binary file:
fseek(fp, 0, SEEK_SET); // beginningfseek(fp, 0, SEEK_END); // endfseek(fp, 10, SEEK_CUR); // 10 bytes forward from current position
long pos = ftell(fp); // current positionWriting Structs
You can write entire structs to binary files:
typedef struct { char name[32]; int score;} Record;
Record r = {"Alice", 95};fwrite(&r, sizeof(Record), 1, fp);Convenient, but you're writing whatever the compiler laid out in memory: the host's byte order, any padding bytes between fields (with whatever junk they held), and, if the struct contains a pointer, an address that means nothing to the next process that reads the file. Real file formats write each field explicitly instead. The runner below does that with a magic number up front and every integer stored big-endian, then reads it back and dumps the raw bytes.
Predict before you run it: how big is a Record in memory, and how many bytes does save() write for Alice with score 95?
36 in memory: 32 bytes of name plus a 4-byte int, with no padding needed since 36 is already a multiple of the int's 4-byte alignment. On disk it's 17: a 4-byte magic, a 4-byte length, the 5 letters of Alice and a 4-byte score. The 27 unused bytes of name never reach the file.
Here's what the convenient version actually puts on disk for Alice on x86-64 Linux. Click each field:
fwrite(&r, sizeof(Record), 1, fp) on x86-64
Click a coloured byte or a field name to decode it
Thirty-six bytes, more than half of them nothing, and an integer whose byte order depends on the machine that wrote it. The runner below writes the same record the careful way.
Worked Example: Reading the Dump
The runner prints the file as hex. Split it at the field boundaries and every byte has a job:
| Bytes | Field | Meaning |
|---|---|---|
52 45 43 31 | magic | the ASCII codes for R, E, C, 1 |
00 00 00 05 | name_len | 5, most significant byte first |
41 6c 69 63 65 | name | A l i c e, no terminator |
00 00 00 5f | score | 0x5f, which is 95 |
Follow put_u32(fp, 95) to see where the last four bytes came from. 95 is 0x0000005f. Shifting right by 24, 16 and 8 leaves 0 each time, and storing into an unsigned char keeps only the low 8 bits, so the array becomes {0x00, 0x00, 0x00, 0x5f}. A bigger score shows the order more clearly: 1000 is 0x000003e8, written as 00 00 03 e8. A raw fwrite(&score, 4, 1, fp) on x86-64 would write e8 03 00 00 instead, lowest byte first, and a big-endian machine reading that would get 3,892,510,720.
load() reverses each step and checks as it goes: wrong magic, a length that won't fit in name, or a file that ends too soon all make it return -1 instead of filling the struct with junk.
What the b Actually Does
On Linux and macOS, nothing: POSIX says the b in "rb" or "wb" is ignored, because text and binary streams are identical there. On Windows, text mode translates \n into the two bytes \r\n on the way out and back again on the way in, and treats a 0x1A byte (Ctrl+Z) as end of file when reading. That's harmless for text and ruinous for binary data. The int 10 is stored as 0a 00 00 00, and in text mode it would hit the disk as 0d 0a 00 00 00, one byte longer. Always write the b for binary files so the same code works everywhere.
When fread returns fewer items than you asked for, the same rule applies as with fgets in Reading Files: check feof(fp) and ferror(fp) to learn whether the file ended or the read failed.
Try It
Use the code editor below to write the scores 95, 1000 and 70000 to a file with put_u32, then read the file back a byte at a time and print each byte in hex. Once that works, swap one put_u32 for a raw fwrite(&score, 4, 1, fp) and spot which four bytes came out backwards.
Challenges
Write a program that counts and prints the number of lines read from stdin.