fread

 

Description

Reads up to count items of size bytes from the input stream and stores them in buffer.

Syntax

size_t fread( void * buffer, size_t size, size_t count, FILE * stream )

Parameters

buffer
Storage location for data
size
Item size in bytes
count
Maximum number of items to be read
stream
Pointer to FILE

Return

fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. Use the feof or ferror function to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged.

Examples

EX1

//The following opens a file named fread.out and writes 25 characters to the file. 
//It then tries to open fread.out and read in 25 characters.If the attempt succeeds,
//the program displays the number of actual items read.

void test_fread()
{
    FILE *stream;
    char list[30];
    int  i, numread, numwritten;
    
    // Open file in text mode:
    stream = fopen( "fread.out", "w+t" );
    if(stream != NULL )
    {
        for ( i = 0; i < 25; i++ )
            list[i] = (char)('z' - i);
        
        // Write 25 characters to stream 
        numwritten = fwrite( list, sizeof( char ), 25, stream );
        printf( "Wrote %d items\n", numwritten );
        fclose( stream );
    }
    else
        printf( "Problem opening the file\n" );
    
    stream = fopen( "fread.out", "r+t" );
    if(stream != NULL )
    {
        // Attempt to read in 25 characters 
        numread = fread( list, sizeof( char ), 25, stream );
        printf( "Number of items read = %d\n", numread );
        printf( "Contents of buffer = %.25s\n", list );
        fclose( stream );
    }
    else
        printf( "File could not be opened\n" );
}

Remark

The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined.

See Also

fwrite

header to Include

origin.h

Reference