13.14. fread()

Read binary data from a file.


#include <stdio.h>
size_t fread(void *p, size_t size, size_t nmemb, FILE *stream);


You might remember that you can call fopen() with the "b" flag in the open mode string to open the file in "binary" mode. Files open in not-binary (ASCII or text mode) can be read using standard character-oriented calls like fgetc() or fgets(). Files open in binary mode are typically read using the fread() function.

All this function does is says, "Hey, read this many things where each thing is a certain number of bytes, and store the whole mess of them in memory starting at this pointer."

This can be very useful, believe me, when you want to do something like store 20 ints in a file.

But wait--can't you use fprintf() with the "%d" format specifier to save the ints to a text file and store them that way? Yes, sure. That has the advantage that a human can open the file and read the numbers. It has the disadvantage that it's slower to convert the numbers from ints to text and that the numbers are likely to take more space in the file. (Remember, an int is likely 4 bytes, but the string "12345678" is 8 bytes.)

So storing the binary data can certainly be more compact and faster to read.

(As for the prototype, what is this size_t you see floating around? It's short for "size type" which is a data type defined to hold the size of something. Great--would I stop beating around the bush already and give you the straight story?! Ok, size_t is probably an int.)

Return Value

This function returns the number of items successfully read. If all requested items are read, the return value will be equal to that of the parameter nmemb. If EOF occurs, the return value will be zero.

To make you confused, it will also return zero if there's an error. You can use the functions feof() or ferror() to tell which one really happened.


// read 10 numbers from a file and store them in an array

int main(void)
    int i;
    int n[10]
    FILE *fp;

    fp = fopen("binarynumbers.dat", "rb");
    fread(n, sizeof(int), 10, fp);  // read 10 ints

    // print them out:
    for(i = 0; i < 10; i++)
        printf("n[%d] == %d\n", i, n[i]);

    return 0;

See Also

fopen(), fwrite(), feof(), ferror()