C library functions -fread()

C Standard Library - <stdio.h>

Description

C Library Functionssize_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)From the given streamstreamRead data intoptrIn the array pointed to.

Declaration

Below is the declaration of the fread() function.

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

Parameter

  • ptr-- This is a pointer to a memory block with a minimum sizesize*nmembpointer to a memory block of bytes.
  • size-- This is the size in bytes of each element to be read.
  • nmemb-- This is the number of elements, each of size size bytes.
  • stream-- This is a pointer to a FILE object that specifies an input stream.

Return Value

The total number of elements successfully read is returned as a size_t object, which is an integer data type. If the total differs from the nmemb parameter, an error may have occurred or the end of the file was reached.

Example

The following example demonstrates the usage of the fread() function.

Example

#include <stdio.h>
#include <string.h>
 
int main()
{
   FILE *fp;
   char c[] = "This is example";
   char buffer[20];
 
   /* Open a file for reading and writing */
   fp = fopen("file.txt", "w+");
 
   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);
 
   /* Find the beginning of the file */
   fseek(fp, 0, SEEK_SET);
 
   /* Read and display data */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);
   
   return(0);
}

Let us compile and run the above program, which will create a filefile.txt, then write contentThis is example. Next we usefseek()Function to reset the write pointer to the beginning of the file, the file content is as follows:

This is example

C Standard Library - <stdio.h>

other extensions