fread : <stdio.h> library function

The function size_t fread(void *ptr, size_t size, size_t count, FILE *stream); reads count number of objects each of size bytes from the given stream and stores them in the block of memory(array) specified by ptr. It copy total size x count bytes from given stream to memory block.

Function prototype of fread

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
  • ptr : This is the pointer to a block of memory having atleast size*count bytes, type-casted to a void pointer.
  • size : This is the size of each element to be read in bytes.
  • count : This is the number of elements to be read from stream, each one with a size of size bytes.
  • stream : A pointer to a FILE object which identifies a stream from where we want to read.

Return value of fread

This function returns the total number of elements successfully read from stream as a size_t(size_t is an unsigned integral type). If either a reading error occurred or the end-of-file was reached then proper indicator is set, which can be checked with ferror and feof, respectively.

C program to show the use of fread function

The following program shows the use of fread function to read a string from stream and stores in a character array.

#include <stdio.h>
#include <string.h>

int main(){
   FILE *file;
   char buff[20]; 
   char *string = "fread C Standard library function";
   
   /* Open file for reading and writing */
   file = fopen("textFile.txt", "w+");

   /* Write data to the file */
   fputs(string, file);

   /* Reset file pointer to the beginning of file */
   fseek(file, 0, SEEK_SET);

   /* Read string from file to a character array */
   fread(buff, strlen(string)+1, 1, file);\
   
   printf("%s\n", buff);
   fclose(file);
   
   return(0);
}

Program Output
fread C Standard library function