Read elements of a given size from a stream
#include <stdio.h> size_t fread( void* buf, size_t size, size_t num, FILE* fp );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The fread() function reads num elements of size bytes each from the stream 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.
Use the feof() and ferror() functions to determine whether the end of the file was encountered or if an input/output error has occurred.
If an error occurs, errno is set to indicate the type of error.
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; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
errno, fopen(), feof(), ferror()