Easy Tutorial
❮ C Exercise Example55 C Examples Sum Prime Numbers ❯

C Library Function - fread()

C Standard Library - <stdio.h>

Description

The C library function sizet fread(void *ptr, sizet size, size_t nmemb, FILE *stream) reads data from the given stream stream into the array pointed to by ptr.

Declaration

Here is the declaration for the fread() function.

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

Parameters

Return Value

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

Example

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

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

int main()
{
   FILE *fp;
   char c[] = "This is tutorialpro";
   char buffer[20];

   /* Open file for both reading and writing */
   fp = fopen("file.txt", "w+");

   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);

   /* Seek to 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's compile and run the above program, which will create a file file.txt and write the content This is tutorialpro to it. Then we use the fseek() function to reset the write pointer to the beginning of the file. The file content will be as follows:

This is tutorialpro

C Standard Library - <stdio.h>

❮ C Exercise Example55 C Examples Sum Prime Numbers ❯