fread()
QNX SDP8.0C Library ReferenceAPIDeveloper
Read elements of a given size from a stream
Synopsis:
#include <stdio.h>
size_t fread( void* buf,
size_t size,
size_t num,
FILE* fp );
Arguments:
- buf
- A pointer to a buffer where the function can store the elements that it reads.
- size
- The size of each element to read.
- num
- The number of elements to read.
- fp
- The stream from which to read the elements.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The fread() function reads num elements of size bytes each from the stream specified by fp into the buffer specified by buf.
Note:
If you're reading and writing large amounts of data, you can improve performance by increasing the size
of the internal buffer that's used for stream I/O.
For more information, see
Adjusting the buffer sizein the entry for fopen().
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 is 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:
Safety: | |
---|---|
Cancellation point | Yes |
Signal handler | No |
Thread | Yes |
Page updated: