int  fread (void * buffer, size_t size, size_t count, FILE * stream);

Read block of data from a stream.
  Read count number of items each one with a size of size bytes from the stream and stores it in the specified buffer.
  Stream's postion indicator is increased by the number of bytes readed.
  Total amount of bytes read is (size x count).


Pointer to the destination structure with a minimum size of (size*count) bytes.
Size in bytes of each item to be read.
Number of items, each one with a size of size bytes.
pointer to an open file.

Return Value.
  The total number of items readed is returned.
  If this number differs from the requested amount (count parameter) an error has occured or End Of File has been reached. To determine what happened call feof or ferror.

  Defined in ANSI-C.


/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

main () {
  FILE * pFile;
  long lSize;
  char * buffer;

  pFile = fopen ( "myfile.txt" , "rb" );
  if (pFile==NULL) exit (1);

  // obtain file size.
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file.
  buffer = (char*) malloc (lSize);
  if (buffer == NULL) exit (2);

  // copy the file into the buffer.
  fread (buffer,1,lSize,pFile);

  /*** the whole file is loaded in the buffer. ***/

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
  This code loads myfile.txt in a buffer, and then terminates.

See also.
  fgetc, fread, fwrite, fopen, fopen

© The C++ Resources Network, 2000