Programming Reference/Librarys
Question & Answer
Q&A is closed
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
fread reads num number of objects from a stream (where each object is size bytes) and places them into the array pointed to by buffer. The return value of the function is the number of read data
/* * fread example code * http://code-reference.com/c/stdio.h/fread */ #include <stdio.h> /* including standard library */ //#include <windows.h> /* uncomment this for Windows */ struct CD_COLLECTION { char album_name[42]; int year; char artist[42]; }; int main (void) { FILE *stream = fopen ("collection.bin","rb"); struct CD_COLLECTION collection[5]; unsigned short i = 0; fread (collection, sizeof(struct CD_COLLECTION), 5, stream); for (i=0; i<5 ; i++) { printf("Album Name: %s\nYear %i\nArtist: %s\n\n",collection[i].album_name, collection[i].year, collection[i].artist); } fclose (stream); return 0; }
to generate the binary file use fwrite
output: ./fread Album Name: Interpret 0 Year 2012 Artist: Mr Unrockable 0 Album Name: Interpret 1 Year 2012 Artist: Mr Unrockable 1 Album Name: Interpret 2 Year 2012 Artist: Mr Unrockable 2 Album Name: Interpret 3 Year 2012 Artist: Mr Unrockable 3 Album Name: Interpret 4 Year 2012 Artist: Mr Unrockable 4