[Previous] [Contents] [Next]

fread()

Read elements from a file

Synopsis:

#include <stdio.h>

size_t fread( void* buf,
              size_t size,
              size_t num,
              FILE* fp );

Library:

libc

Description:

The fread() function reads num elements of size bytes each from the stream specified by fp into the buffer specified by buf.

Returns:

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

Use the feof() and ferror() functions to determine whether the end of the file was encountered or if an input/output error has occurred.

Errors:

If an error occurs, errno will be set to indicate the type of error.

Examples:

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>
#include <stdlib.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( struct student_data ), 1, fp ) );
}

int main( void )
{
    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 );
        
        return EXIT_SUCCESS;
    }
    
    return EXIT_FAILURE;
}

Classification:

ANSI

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

See also:

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


[Previous] [Contents] [Next]