fread() function in C++ program


Given the task is to show the working of fread() in C++. In this article we will also look into the different parameters which are passed to fread() and what this function returns.

fread() is an inbuilt function of C++ which reads a block of data from the stream. This function counts the number of objects each with the size of “size” bytes from the stream and stores them in buffer memory, then position pointer advanced by the total amount of bytes read. The amount of bytes read if successful will be size *count.

Syntax

fread(void *buffer, size_t size, size_t count, FILE *file_stream);

Parameters

This function will require all 4 parameters. Let’s understand the parameters.

  • buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored.

  • size − It defines the size of each element to be read in bytes. (size_t is unsigned int).

  • count − The number of elements to be read.\

  • file_stream − Pointer of the file stream from which we want to read the bytes.

Return Value

The number of elements successfully read is returned.

If any reading error occurs or it reaches end-of-file the number of elements returned will vary from the count variable.

Example

#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main() {
   FILE* file_stream;
   char buf[100];
   file_stream = fopen("tp.txt", "r");
   while (!feof(file_stream)) //will read the file {
      // will read the contents of the file.
      fread(buf, sizeof(buf), 1, file_stream);
      cout << buf;
   }
   return 0;
}

Assuming the tp.txt file have the following content

tutorialspoint

Contribution

anything here

Output

If we run the above code it will generate the following output −

tutorialspoint
Contribution
anything here

Let’s take example and check the output when the count is zero and the size is zero.

Example

 Live Demo

#include <iostream>
#include <cstdio>
using namespace std; int main() {
   FILE *fp;
   char buffer[100];
   int retVal;
   fp = fopen("tpempty.txt","rb");
   retVal = fread(buffer,sizeof(buffer),0,fp);
   cout << "The count = 0, then return value = " << retVal << endl;
   retVal = fread(buffer,0,1,fp);
   cout << "The size = 0, then value = " << retVal << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

The count = 0, then return value = 0
The size = 0, then value = 0

Updated on: 28-Feb-2020

677 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements