×

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language; it was developed by Bjarne Stroustrup.

Features of C++

  1. High-level language.
  2. Object-oriented programming language
  3. Portable
  4. Graphical user interference
  5. Simple
  6. Structured programming language

C++ language is somewhat the same as that of other languages like C, Java, and C#.

fread() in C++

In C++ programming, the fread() function reads the data from the bunch along the stream or the characters from the stream. Initially, the function tends to read the count of the number of objects, each having a size of size bytes in the input stream.

fread() Prototype

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

The above one is the prototype for the fread() function, or it can be called the prototype for the function fread().

There are four parameters listed in that format that are:

  1. Size: It refers to the size of each object or character and is represented in Bytes.
  2. Count: Counts the number of objects or characters.
  3. Stream: used to read data from the stream.
  4. Buffer: It is used to store the objects or the characters which point to the block of memory.

The behavior is undefinable if the items are not easily duplicable. A call to fread() will return zero and do nothing else if the size or count is zero. If there is a problem while reading the file, the value of the file position indicates the stream is undefined.

fread() return value

Returns the number of objects or characters that are being read successfully. Suppose the return value is less than the count. It throughs an error. The fread() function also does not act if the return value is written as zero.

C++ Program for fread() function

#include <iostream>
#include <cstdio>
using namespace std;


int main()
{
    FILE *fileopen;
    char buff[100];
    fileopen = fopen("demo.txt","rb");
    while(!feof(fileopen))
    {
        fread(buff,sizeof(buff),1,fileopen);
        cout << buff;
    }
    
    return 0;
}

Output

Father Occupation: Business
Mother Occupation: Home Wife
Grand Father Occupation: Farmer
Your Occupation: Student

Note: Your output may vary because you may enter different data, and it will display different results on the terminal of your computer or the system.

Explanation of the above program:

Here we specified rb in the code in the function fopen() to read the code in the binary format after the open. First, you have to create a text file in your computer in a folder to execute the program. From that file, the program which you have written will open and read the file in binary format. Here we used the header file of #include<cstdio>, which imports all the functions along with the fread() function. Here fopen() is used to open the file, and fread() is used to convert the text into binary format and read the text. Cout is used to print the information or the result in the terminal. The text file contains the above data of the output, which was printed as the output.

C++ Program for fread() function:

#include <iostream>
#include <cstdio>
using namespace std;


int main()
{
    FILE *fileopen;
    char buff[100];
    int printVal;
    
    fileopen = fopen("demo.txt","rb");


    printVal = fread(buff,sizeof(buff),0,fileopen);
    cout << " If count = 0, return value will be = " << printVal << endl;


    printVal = fread(buff,0,1,fileopen);
    cout << " If size = 0, return value will be = " << printVal << endl;
    
    return 0;
}

Output:

If count = 0, return value will be = 0
If size = 0, return value will be = 0

Explanation of the above program:

We already discussed that the return value of the program would be zero if the count value and size value were zero. In the above program, we followed a particular syntax that was mentioned in the fread() function prototype.

Conclusion

Hence the function is used to read the text of the file that has been created and print the output in the terminal and reads the number of objects in the input stream. By using the fread() function, we cannot alter the text file, but by the fwrite() function, we can alter the text of the text file that has been created. In creating the fread() function, we have to allocate some memory.


Related Topics

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.