C++ fread()

fread() prototype

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

The fread() function reads count number of objects, each of size size bytes from the given input stream. It is similar to calling fgetc() size times to read each object. According to the number of characters read, the file position indicator is incremented.

The resulting value of the file position indicator for the stream is indeterminate if any error occurs while reading the file.

If the objects are not trivially copyable, the behavior is undefined.

If the size or count is zero, a call to fread will return zero and no other action is performed.

It is defined in <cstdio> header file.

fread() Parameters

  • buffer: Pointer to the block of memory to store the objects.
  • size: Size of each objects in bytes.
  • count: The number of objects to read.
  • stream: The file stream to read the data from.

fread() Return value

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

Example 1: How fread() function works

#include <iostream>
#include <cstdio>

using namespace std;

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

Suppose the file contains following data:

Dennis Ritchie : C
Bjarne Stroustrup : C++
Guido van Rossum : Python
James Gosling : Java

When you run the program, the output will be:

Dennis Ritchie : C
Bjarne Stroustrup : C++
Guido van Rossum : Python
James Gosling : Java

Example 2: How fread() function works when either count or size is zero

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    FILE *fp;
    char buffer[100];
    int retVal;
    
    fp = fopen("data.txt","rb");
    
    /*  when count is zero */
    retVal = fread(buffer,sizeof(buffer),0,fp);
    cout << "When count = 0, return value = " << retVal << endl;
    
    /*  when size is zero */
    retVal = fread(buffer,0,1,fp);
    cout << "When size = 0, return value = " << retVal << endl;
    
    return 0;
}

When you run the program, the output will be:

When count = 0, return value = 0
When size = 0, return value = 0
Did you find this article helpful?