User Tools

Site Tools


c:stdio.h:fread

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

c:stdio.h:fread [2013/01/22 22:02] (current)
Line 1: Line 1:
 +{{keywords>wiki library source code example reference}}
 +===== fread =====
 +
 +<code c>
 +    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
 +</code>
 +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
 +
 +===== C Sourcecode Example =====
 +<code c>
 +/* 
 + * 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;
 +}
 +</code>
 +
 +==== fread output example ====
 +**to generate the binary file use [[c:stdio.h: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
 +    
  
advertising
c/stdio.h/fread.txt · Last modified: 2013/01/22 22:02 (external edit)

Impressum Datenschutz