C++ fread() Function

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The fread in C++ is a function that reads a block of data from a stream. This function first counts the number of objects in the stream with sizes of size bytes and then stores them in the buffer memory, then advances the position pointer by the total number of bytes read. If successful, the number of bytes read will be size * count.

Syntax of fread() Function in C++

The syntax of fread in C++ is as follows:

Parameters of fread() Function in C++

The fread in C++ will require four parameters, and they are as follows:

  1. buffer:- This is a pointer to a buffer memory block that stores the bytes read from the stream.
  2. size:- It specifies the size in bytes of each element to be read. (size_t is an unsigned integer).
  3. count:- The total number of elements to read.
  4. fp:- The file stream pointer from which we want to read the data.

Return Value of fread() Function in C++

The fread() function returns the count of objects successfully read. If an error or an end-of-file condition occurs, the return value may be less than the count.

How does fread() Function in C++ Work?

Let's take two examples to understand the working of the fread() function.

The above fread() function will read 1000 elements of 1 byte each.

This fread() function will read one 1000-byte element.

Examples

Example 1: Program to Read a File abc.txt using fread() Function

Suppose the text file “abc.txt” contains the following content.

Output:

Explanation:

In the above example, we are reading 1 element of size sizeof(buffer) from the file abc.txt, where the buffer is the character array that will store the data read by the fread() function.

Example 2: C++ Program to illustrate fread() Function When the Element's Size or Count Equals Zero

Output:

Explanation:

In the above example, first, we give a count of the element to be read 0 and then give the element size to be read 0. In both cases, the total number of bytes to be read is zero, so the fread() function didn’t read anything and returned 0.

Conclusion

  • The fread() in C++ is a function that reads a block of data from a stream.
  • The fread() function takes in a file pointer "fp" and reads "count" elements, each with a size of "size". This will store the contents into a buffer, passed as a void* pointer.
  • The fread() function returns the count of successfully read elements.