Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 135 ยท File Input and Output

Binary Files

Store raw bytes in C with fread and fwrite, jump around a file with fseek, ftell and rewind, save arrays of structs as records, and keep files portable across machines.

A text file stores the number 1000000 as seven characters, '1' followed by six '0's. A binary file stores it the way it sits in memory: four bytes for an int. Binary files are smaller, much faster to read and write (no formatting or parsing), and let you jump straight to record number 5,000 without reading the 4,999 before it. Images, audio, databases, save games and executables are all binary files.

The price is that binary data is not human-readable and not automatically portable: a file written on one machine may be read differently on another. This lesson covers the core functions fwrite, fread, fseek, ftell and rewind, shows how to keep a file of fixed-size records, and explains the portability traps (byte order, padding, type sizes) and how to avoid them.

You should be comfortable with File Handling Basics and Structures before you start.

Opening a file in binary mode

Add b to the mode string: "rb", "wb", "ab", "r+b" (read and write an existing file), "w+b" (create, then read and write). On Linux and macOS the b changes nothing, but on Windows text mode converts \n to \r\n on output and stops reading at a Ctrl+Z byte, which corrupts binary data. Always write the b so your code works everywhere.

fwrite and fread

Both functions move whole blocks of bytes between memory and a file:

C
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);

They transfer count items of size bytes each, and return how many complete items were transferred. That return value is your error check: if it's less than count, fwrite failed (disk full, for example), and fread hit the end of the file or an error, which you tell apart with feof and ferror.

C Saving and loading an array of ints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Asking for 20 items when the file has 10 isn't an error: fread returns 10 and sets the end-of-file indicator. The file is exactly 40 bytes, the in-memory size of ten 4-byte ints. Small numbers like these would actually be shorter as text (26 bytes with spaces and a newline), but in binary every int costs exactly 4 bytes, while a value like -2000000000 needs 11 characters as text, and the reader never has to parse anything.

Tip: Pass the element size as sizeof array[0] or sizeof *ptr rather than sizeof(int). If you later change the array's type, the size follows automatically.

Writing structs as fixed-size records

Because a struct has a fixed size, a file of structs is a simple database table: record i starts at byte i * sizeof(struct record). You can write one struct, an array of them, or append more later.

C A file of product records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

sizeof(struct product) is 40 here, not the 36 bytes you get by adding up the members (4 + 20 + 8 + 4). The double already starts at offset 24, a multiple of 8, but the compiler adds 4 bytes of padding at the end so that the struct's size is a multiple of the double's 8-byte alignment; that keeps every element of an array of structs aligned (Padding and Alignment explains the rules). The padding bytes are written to the file too, with whatever values happened to be in memory. That's harmless for reading back on the same machine, but it's one of the reasons raw struct files aren't portable.

Warning: Never fwrite a struct that contains pointers, such as char *name. The file would store the pointer's address, not the text it points to, and that address means nothing in the next run. Store strings in fixed-size char arrays, or write the length followed by the characters.

Moving around: fseek, ftell and rewind

Every open file has a file position: the byte offset where the next read or write happens. Three functions control it:

Call Effect
fseek(fp, offset, SEEK_SET) go to offset bytes from the start
fseek(fp, offset, SEEK_CUR) move offset bytes from the current position (may be negative)
fseek(fp, offset, SEEK_END) go to offset bytes from the end (usually 0 or negative)
ftell(fp) return the current position as a long (-1L on error)
rewind(fp) go back to the start and clear the error and end-of-file flags

fseek returns 0 on success. It also clears the end-of-file indicator, so you can read again after hitting the end. A classic use is finding a file's size: seek to the end, ask for the position, then rewind. That's reliable for binary streams on common systems, although the C standard technically doesn't promise SEEK_END support for binary files.

With fixed-size records, random access is just multiplication. This program reads the third record directly, updates one record in place with mode "r+b", and prints the file size:

C Random access to records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The update changed 16 bytes in the middle of the file without touching the other records; that's the big advantage over text files. Seeking past the end (record 9) succeeds, but the following fread returns 0, which read_record reports as failure.

Note: When a file is open for both reading and writing ("r+b", "w+b"), C requires an fseek, fsetpos, rewind or fflush between a write and a following read, and an fseek/rewind between a read and a following write. The helper functions above always seek first, so they follow the rule automatically. ftell returns a long, which is 32 bits on Windows; for files over 2 GB, use POSIX fseeko/ftello or Windows _fseeki64.

Portability: byte order, padding and sizes

A raw struct dump depends on three things that differ between platforms:

  1. Type sizes. int is 4 bytes nearly everywhere today, but long is 8 bytes on 64-bit Linux and macOS and 4 bytes on 64-bit Windows. Use the fixed-width types from <stdint.h> (int32_t, uint16_t, โ€ฆ; see Integer Types) in anything you save.
  2. Padding. Different compilers and ABIs may pad the same struct differently.
  3. Byte order (endianness). A little-endian CPU (x86, most ARM systems) stores the least significant byte first; a big-endian one stores the most significant byte first. Network protocols and many file formats use big-endian.

You can see the byte order of the machine running your code by looking at an integer's bytes through an unsigned char pointer, which is always allowed in C:

C Seeing the byte order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Our server is x86-64, so it prints 44 33 22 11 and says little-endian.

The portable solution is to define the file format byte by byte and convert values with shifts. Shifts work on values, not on memory, so this code produces the same file on every machine:

C A portable big-endian format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This little format has the parts every serious binary format has:

  • A magic number (SCR1) so a reader can reject files that aren't of this type. PNG files, for example, always start with the same 8 bytes.
  • A version (the 1 in the magic here) so the format can change later.
  • A count that's validated before use. Data from a file is untrusted input: a corrupt or malicious file could claim four billion records and make you allocate or loop forever.
  • Explicit byte order and sizes for every field, independent of struct layout.

Raw fwrite of structs is still fine for temporary files, caches and data that never leaves one program on one machine. For anything you share, archive or send over a network, define the bytes. (Text formats like CSV or JSON are another portable choice when speed and size matter less.)

Copying any file in chunks

fread and fwrite are also the fastest way to copy a file of any type. Read a buffer, write exactly the number of bytes you got, and repeat:

C
unsigned char buf[8192];
size_t n;
while ((n = fread(buf, 1, sizeof buf, in)) > 0) {
    if (fwrite(buf, 1, n, out) != n) {
        perror("write");
        break;
    }
}
if (ferror(in)) {
    perror("read");
}

Using an item size of 1 makes the return value a byte count, which is what you want when the data isn't a whole number of items.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file is 10 bytes long. What does fread(buf, 4, 3, fp) return?

    fread returns the number of complete items. Two 4-byte items fit in 10 bytes; the last 2 bytes are a partial item and are not counted.
  2. 2. Why is sizeof(struct { int id; char name[20]; double price; int stock; }) 40 and not 36 on our server?

    The struct's size must be a multiple of its strictest member alignment (8 for the double), so the compiler adds 4 padding bytes at the end. That padding becomes part of the file, which is one reason struct dumps aren't portable.
  3. 3. How do you read record number 7 (counting from 0) of a file of struct rec records?

    fseek offsets are in bytes, so multiply the record index by the record size.
  4. 4. On a little-endian machine, which bytes does fwrite(&v, sizeof v, 1, fp) write for uint16_t v = 0x0102?

    A little-endian CPU stores the least significant byte first, so memory (and therefore the file) holds 02 then 01. Shift-based helpers make the order explicit.
  5. 5. Why shouldn't you fwrite a struct that contains a char * field?

    fwrite copies the struct's bytes as they are. A pointer's bytes are an address in this process's memory; the string itself is somewhere else and is never written.

Summary

  • Open binary files with a b in the mode ("rb", "wb", "r+b", "w+b"); it matters on Windows.
  • fwrite(ptr, size, count, fp) and fread(...) move blocks of bytes and return the number of complete items transferred; compare it with count, and use feof/ferror to explain a short read.
  • Files of fixed-size structs give you random access: record i starts at i * sizeof(record).
  • fseek (with SEEK_SET, SEEK_CUR, SEEK_END), ftell and rewind move and report the file position; seek between switching from writing to reading on update streams.
  • Raw struct files depend on type sizes, padding and byte order. For portable files, use <stdint.h> types and write each field byte by byte with shifts, behind a magic number and version.
  • Validate every count and size you read from a file before using it.

Next: Error Handling, where you'll report failures with errno, perror and strerror and clean up properly when something goes wrong.