Name

fread

Synopsis

Reads a number of objects from a file

#include <stdio.h>
size_tfread( void * restrict buffer, size_t size, size_t n,
              FILE * restrict fp );

The fread() function reads up to n data objects of size size from the specified file, and stores them in the memory block pointed to by the buffer argument. You must make sure that the available size of the memory block in bytes is at least n times size. Furthermore, on systems that distinguish between text and binary file access modes, the file should be opened in binary mode.

The fread() function returns the number of data objects read. If this number is less than the requested number, then either the end of the file was reached or an error occurred.

Example

typedef struct {
  char name[64];
  /* ... more members ... */
} item;

#define CACHESIZE 32                  // Size as a number of array elements.

FILE *fp;
int readcount = 0;
item itemcache[CACHESIZE];            // An array of "items".

if (( fp = fopen( "items.dat", "r+" )) == NULL )
  perror( "Opening data file" ), return -1;

/* Read up to CACHESIZE "item" records from the file.*/

readcount =fread( itemcache, sizeof (item), CACHESIZE, fp );

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.