User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdio.h:fread

fread

    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

C Sourcecode Example

/* 
 * 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;
}

fread output example

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
  

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
c/stdio.h/fread.txt · Last modified: 2013/01/22 22:02 (external edit)

Impressum Datenschutz