Skip to content
Related Articles

Related Articles

Improve Article

fread() function in C++

  • Difficulty Level : Medium
  • Last Updated : 16 Feb, 2021
Geek Week

The fread() function in C++ reads the block of data from the stream. This function first, reads the count number of objects, each one with a size of size bytes from the given input stream. 
The total amount of bytes reads if successful is (size*count). According to the no. of characters read, the indicator file position is incremented. If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0.
Syntax : 
 

size_t fread(void * buffer, size_t size, size_t count, FILE * stream)

Parameter : The function accepts four mandatory parameters which are described as below: 
 

  • buffer: it specifies the pointer to the block of memory with a size of at least (size*count) bytes to store the objects.
  • size: it specifies the size of each object in bytes. size_t is an unsigned integral type.
  • count: it specifies the number of elements, each one with a size of size bytes.
  • stream: it specifies the file stream to read the data from.

Return Value: The function returns the number of objects read successfully. If an error occurs, the return value can be less than the count.
Below programs illustrate the above function: 
Program 1: 
 

CPP




// C++ program to illustrate fread() function
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
 
int main()
{
    FILE* file_;
    char buffer[100];
    file_ = fopen("g4g.txt", "aman");
    while (!feof(file_)) // to read file
    {
        // function used to read the contents of file
        fread(buffer, sizeof(buffer), 1, file_);
        cout << buffer;
    }
    return 0;
}

Suppose the file g4g.txt contains following data: 
 



Geeks : DS-ALgo 
Gfg : DP 
Contribute : writearticle 

Then, when you will run the program, the output will be 
 

Harry Potter : Specs
Hermione : Smart
Weasley : FlyingCar
Dumbledore : Wand

Program 2 : 
 

CPP




// C++ program to illustrate fread() function
// when file's size or count is equal to 0
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
 
int main()
{
    FILE* file_;
    char buffer[100];
 
    file_ = fopen("g4g.txt", "aman");
    cout << "count = 0, return value = " <<
    fread(buffer, sizeof(buffer), 0, file_);
    cout << "\nsize = 0, return value = " <<
    fread(buffer, 0, 1, file_) << endl;
    return 0;
}
Output: 
count = 0, return value = 0
size = 0, return value = 0

 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :