Course contentsShow
← C
Lesson 726 of 1,21910. Input and OutputFree lesson

Reading raw bytes with fread

Reading raw bytes with fread

What you'll learn: How to use the fread function to pull exact chunks of binary data from a file directly into your program's memory.

Thinking in Chunks

When we use fprintf or fscanf, C treats data as human-readable text. But computers don't naturally speak "text"; they speak in bytes. Imagine a file is a long conveyor belt carrying identical boxes. Instead of opening every box to see what’s inside, you just want to grab five boxes and put them on your shelf.

This is what fread does. It doesn't care if the data represents a number, a pixel, or a piece of music. It simply copies a specific number of bytes from the file into a variable or an array in your code.

The fread Blueprint

The fread function requires four pieces of information to do its job:

  1. Where to put it: A pointer to the variable or array (the destination).
  2. Size of one item: How big is a single "box"? (usually calculated with sizeof).
  3. Number of items: How many "boxes" do you want to grab?
  4. The source: The file pointer (FILE *) you opened earlier.

A Concrete Example

Imagine we have a binary file containing three int values. We want to read them all at once into an array.

#include <stdio.h>

int main() {
    FILE *file = fopen("data.bin", "rb"); // 'rb' means read binary
    if (file == NULL) return 1;

    int numbers[3];
    
    // Read 3 items, each the size of an integer
    size_t itemsRead = fread(numbers, sizeof(int), 3, file);

    if (itemsRead == 3) {
        printf("Successfully read: %d, %d, %d\n", numbers[0], numbers[1], numbers[2]);
    }

    fclose(file);
    return 0;
}

In this snippet, fread looks at the file, grabs enough bytes to fill three integers, and dumps them directly into the numbers array. It returns the number of items it successfully grabbed. If itemsRead is less than 3, we know the file ended early or an error occurred.

Why use it?

Speed and precision. Because fread does not perform any "translation" (like turning the character '1' into the integer 1), it is incredibly fast. It is the gold standard for loading game assets, images, or saved states where you need the data exactly as it was stored on the disk.

Key takeaway

Use fread to copy raw blocks of memory from a binary file directly into your variables without any text translation.