Course contentsShow
← C
Lesson 1218 of 1,21916. Practice and ProjectsFree lesson

Loading data from a binary file

Loading data from a binary file

What you'll learn: How to efficiently restore an entire array of data structures from a disk into memory using fread.

In the previous lessons, we saved our data store to a file. Now, we need to bring it back to life. Think of saving a file like packing a suitcase; loading the file is like unpacking it when you arrive at your destination. Because we saved our data in binary format, we don't need to parse text or convert strings back into numbers. We simply pour the raw bytes from the file directly back into our memory.

The fread function

To read our data, we use the fread function. It works as the mirror image of fwrite. It takes four arguments: where to put the data, how big each item is, how many items to read, and the file pointer.

The magic of binary loading is that one single fread call can populate an entire array of struct objects. You don't need a loop to read every single member variable one by one.

Implementation in our Data Store

In our project, we have an array of Record structures. When the program starts, we want to open our .dat file and fill that array.

#include <stdio.h>

typedef struct {
    int id;
    float value;
} Record;

#define MAX_RECORDS 100

void load_database(Record db[], int *count) {
    FILE *file = fopen("database.dat", "rb"); // 'rb' means Read Binary
    
    if (file == NULL) {
        printf("No existing database found. Starting fresh.\n");
        *count = 0;
        return;
    }

    // fread returns the number of items successfully read
    // We try to fill the entire array
    *count = fread(db, sizeof(Record), MAX_RECORDS, file);

    printf("Loaded %d records successfully.\n", *count);
    fclose(file);
}

Why this is efficient

When you use fscanf to read a text file, the computer has to look at every character, decide if it's a digit or a letter, and then calculate the numerical value. With fread, the computer acts like a shovel. It picks up a chunk of bytes from the hard drive and drops them into your RAM.

The structure of the data on the disk is identical to the structure in your memory, so the CPU doesn't have to do any "thinking." This makes binary loading the fastest way to handle local data storage in C.

Key takeaway

Binary loading with fread is a high-speed "bulk transfer" that restores complex data structures into memory exactly as they were saved.