| << Prev | Beej's Guide to C | Next >> |
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
But wait--can't you use fprintf() with the "%d"
format specifier to save the
So storing the binary data can certainly be more compact and faster to read.
(As for the prototype, what is this
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
fclose(fp);
// print them out:
for(i = 0; i < 10; i++)
printf("n[%d] == %d\n", i, n[i]);
return 0;
}
fopen(), fwrite(), feof(), ferror()
| << Prev | Beej's Guide to C | Next >> |