C fread()

The fread() function is defined in the stdio.h header file. It helps to read the data from the given specified stream into the array. The starting address of the memory location where data need to be stored after file reading is specified by the pointer.


size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); #where stream should be a file pointer

 

fread() Parameters: 

The fread() function takes four parameters. This function is mainly used for reading binary data, it is a complementary function of fwrite().

Parameter Description Required / Optional
ptr the pointer to a block of memory with a minimum size of size*nmemb bytes Required
size size in bytes of each element to be read Required
nmemb the number of elements, each one with a size of size bytes Required
stream the pointer to a FILE object that specifies an input stream Required

fread() Return Value

The return value of fread() function is the total number of elements successfully read. It is returned as a size_t object, which is an integral data type.

Input Return Value
successful integer value equivalent to nmemb
error or EOF a value less than nmemb

Examples of fread() 

Example 1: Working of fread() function in C?


#include <stdio.h>
#include <string.h>
int main()
{
   FILE *pnt;
   char chr[] = "C Programming";
   char buf[100];

   /* Open file */
   pnt = fopen("myfile.txt", "w+");

   /* Write data*/
   fwrite(chr, strlen(chr) + 1, 1, pnt);


   fseek(pnt, 0, SEEK_SET);

   /* Read and display data */
   fread(buf, strlen(chr)+1, 1, pnt);
   printf("%s\n", buf);
   fclose(pnt);
   
   return(0);
}

Output:


C Programming

Example 2: How fread() works in C?


#include <stdio.h>

int main (){
  int buf;
  int val = 2431;
  // Creating file and storing value
  FILE * stream;
  stream = fopen("myfile.txt", "w");
  fwrite(&val;, sizeof(int), 1, stream);
  fclose(stream);

  // Reading value from file
  stream = fopen("myfile.txt", "r");
  fread(&buf;, sizeof(int), 1, stream);
  printf("High score readed is: %d\n",buf);
  fclose(stream);

  return(0);
}

Output:


High score readed is:2431