Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

C++ fread() Function

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

File operations are a vital part of programming, and C++ provides a robust set of functions to handle these tasks. One such function is fread(), a powerful tool used for reading data from files. This function is actually a part of the C library, but it can be used in C++ as well. 

c++ fread() function

Let's delve deeper into understanding this function.

Understanding the fread() Function

fread() is a built-in function in the C library that reads data from a file and stores it in an array or a structure. The function reads binary data directly, which makes it much faster and more efficient than other file-reading functions that read data as text.

Syntax of fread()

The syntax of fread() is as follows:


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

Here's what the parameters mean:

  • ptr: This is a pointer to the block of memory where the read data will be stored.
     
  • size: This is the size (in bytes) of each element to be read.
     
  • count: This is the number of elements to be read.
     
  • stream: This is a pointer to the file from which the data will be read.

The fread() function will return the number of items successfully read from the file. If this number is less than count, it can mean either an error occurred or the end of file (EOF) was reached.

Using fread()

Here's a simple program demonstrating the use of fread() in C++:

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


int main() {
    FILE *fp = fopen("test.bin", "rb");
    if (fp == NULL) {
        cout << "File could not be opened!" << endl;
        return 1;
    }
    
    int buffer[10];
    size_t res = fread(buffer, sizeof(int), 10, fp);
    
    if (res < 10) {
        if (feof(fp))
            cout << "End of file reached!" << endl;
        else
            cout << "An error occurred!" << endl;
    }
    
    for(int i = 0; i < res; i++) {
        cout << buffer[i] << endl;
    }


    fclose(fp);
    return 0;
}

In this program, we open a binary file named test.bin for reading. We then attempt to read 10 integers from the file into an array named buffer. If fewer than 10 integers are read, the program will check if it's because the end of the file was reached or because of an error. It then prints the integers that were read.

Also read -  File Handling in CPP

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is the fread() function used for in C++?

The fread() function is used to read binary data from a file directly into memory.

What does the return value of fread() signify?

The return value of fread() signifies the number of items successfully read from the file.

Can fread() be used for text files?

While fread() can technically be used for any type of file, it's best used with binary files as it reads data in binary format.

Conclusion

Understanding and using the fread() function effectively can greatly enhance your ability to work with binary files in C++. It's a fast and efficient function, suitable for situations where large amounts of binary data need to be read. 
Here are more articles that are recommended to read:


You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts.

Happy Learning!

Topics covered
1.
Introduction
2.
Understanding the fread() Function
2.1.
Syntax of fread()
2.2.
Using fread()
3.
Frequently Asked Questions
3.1.
What is the fread() function used for in C++?
3.2.
What does the return value of fread() signify?
3.3.
Can fread() be used for text files?
4.
Conclusion