fread() — Read Items

Format

#include <stdio.h>
size_t fread(void *buffer, size_t size, size_t count, FILE *stream);

Language Level: ANSI

Threadsafe: Yes.

Description

The fread() function reads up to count items of size length from the input stream and stores them in the given buffer. The position in the file increases by the number of bytes read.

Return Value

The fread() function returns the number of full items successfully read, which can be less than count if an error occurs, or if the end-of-file is met before reaching count. If size or count is 0, the fread() function returns zero, and the contents of the array and the state of the stream remain unchanged.

The value of errno can be set to:

Value
Meaning
EGETANDPUT
A read operation that was not permitted occurred after a write operation.
ENOREC
Record is not found.
ENOTREAD
The file is not open for read operations.
ERECIO
The file is open for record I/O.
ESTDIN
stdin cannot be opened.
ETRUNC
Truncation occurred on the operation.
EIOERROR
A non-recoverable I/O error occurred.
EIORECERR
A recoverable I/O error occurred.

Use the ferror() and feof() functions to distinguish between a read error and an end-of-file.

When using fread() for record input, set size to 1 and count to the maximum expected length of the record, to obtain the number of bytes. If you do not know the record length, you should set size to 1 and count to a large value. You can read only one record at a time when using record I/O.

Example that uses fread()

This example attempts to read NUM_ALPHA characters from the file myfile. If there are any errors with either fread() or fopen(), a message is printed.

#include <stdio.h>
 
#define NUM_ALPHA  26
 
int main(void)
{
  FILE * stream;
  int num;       /* number of characters read from stream */
 
  /* Do not forget that the '\0' char occupies one character too! */
  char buffer[NUM_ALPHA + 1];
 
  if (( stream = fopen("mylib/myfile", "r"))!= NULL )
  {
    memset(buffer, 0, sizeof(buffer));
    num = fread( buffer, sizeof( char ), NUM_ALPHA, stream );
    if ( num ) {  /* fread success */
      printf( "Number of characters has been read = %i\n", num );
      printf( "buffer = %s\n", buffer );
      fclose( stream );
    }
    else {  /* fread failed */
      if ( ferror(stream) )    /* possibility 1 */
        perror( "Error reading myfile" );
      else if ( feof(stream))  /* possibility 2 */
        perror( "EOF found" );
    }
  }
  else
    perror( "Error opening myfile" );
 
}

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]