read elements of a given size from a file


#include <stdio.h>
size_t fread( void *buf, size_t elsize,
          size_t nelem, FILE *fp );


The fread() function reads nelem elements of elsize bytes each from the file specified by fp into the buffer specified by buf.


The number of complete elements successfully read. This value may be less than the requested number of elements.

The feof() and ferror() functions can be used to determine whether the end of the file was encountered or if an input/output error has occurred. When an error has occurred, errno indicates the type of error detected.


The following example reads a simple student record containing binary data. The student record is described by the struct student_data declaration.

#include <stdio.h>

struct student_data {
    int  student_id;
    unsigned char marks[10];

size_t read_data( FILE *fp, struct student_data *p )
    return( fread( p, sizeof(*p), 1, fp ) );

void main()
    FILE *fp;
    struct student_data std;
    int i;

    fp = fopen( "file", "r" );
    if( fp != NULL ) {
      while( read_data( fp, &std) != 0 ) {
        printf( "id=%d ", std.student_id );
        for( i = 0; i < 10; i++ )
          printf( "%3d ", std.marks[ i ] );
        printf( "\n" );
      fclose( fp );



Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fopen(), feof(), ferror()