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

Verifying bytes read vs expected

Verifying bytes read vs expected

What you'll learn: How to use the return value of fread to ensure your program successfully read the amount of data you requested.

When you ask a friend to grab five apples from the store, you don't just assume they succeeded; you count the apples when they get back. Working with binary files in C requires the same skepticism. Because binary files often contain critical structured data (like image pixels or save-game coordinates), assuming a read operation worked perfectly is a recipe for memory corruption and crashes.

The Return Value of fread

The fread function doesn't just silently move data from a file into your variables. It returns a value of type size_t representing the number of elements successfully read. If you ask for 10 integers and the function returns 10, everything is perfect. If it returns 7, you have a problem: you’ve reached the end of the file unexpectedly, or a hardware error occurred.

If you ignore this return value and proceed to use those 10 "integers," the last three will contain "garbage" data—whatever happened to be in that memory location previously.

Implementation in Code

Always store the result of fread in a variable and compare it against your expected count before processing the data.

#include <stdio.h>

struct GameStats {
    int score;
    int level;
};

int main() {
    FILE *file = fopen("save.dat", "rb");
    if (file == NULL) return 1;

    struct GameStats player;
    
    // We want to read 1 element of size 'struct GameStats'
    size_t itemsRead = fread(&player, sizeof(struct GameStats), 1, file);

    // Verify if we actually got what we asked for
    if (itemsRead < 1) {
        printf("Error: Could not read full save data. File might be truncated.\n");
    } else {
        printf("Success! Player is at level %d.\n", player.level);
    }

    fclose(file);
    return 0;
}

Why This Matters

In text files, a missing character might just be a typo. In binary files, a single missing byte shifts every following byte out of its proper alignment. If you expect a 4-byte integer but the file ends after 2 bytes, your program will interpret random memory as data. By verifying the bytes read, you create a "fail-safe" that stops the program before it acts on corrupted information.

Key takeaway

Always compare the return value of fread to your requested count to prevent your program from processing incomplete or "garbage" data.