w3resource

C fread() function

C library function - fread()

The fread() function shall read into the array pointed to by pointer up to nitems elements whose size is specified by size in bytes, from the stream pointed to by stream.

Syntax:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

fread() Parameters:

Name Description Required /Optional
ptr This is the pointer to a block of memory with a minimum size of size*nmemb bytes. Required
size This is the size in bytes of each element to be read. Required
nmemb This is the number of elements, each one with a size of size bytes Required
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value from fread()

  • Upon successful completion, fread() shall return the number of elements successfully read which is less than nitems only if a read error or end-of-file is encountered. If size or nitems is 0, fread() shall return 0 and the contents of the array and the state of the stream remain unchanged. Otherwise, if a read error occurs, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

Example: fread() function

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

#include <stdio.h>
 
#define NUM_ALPHA  30
 
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("test.txt", "r"))!= NULL )
  {
    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 test.txt" );
      else if ( feof(stream))  /* possibility 2 */
        perror( "EOF found" );
    }
  }
  else
    perror( "Error opening myfile" );
 
}

Output:

Number of characters has been read = 23
buffer = Important information

C Programming Code Editor:

Previous C Programming: C fopen()
Next C Programming: C freopen()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdio/c_library_method_fread.php