fread()

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 );

Since:

BlackBerry 10.0.0

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.

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:

ANSI, POSIX 1003.1

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

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus