C++

Fread C++

File handling is one of the essential parts of all programming languages. Writing small and simple code, that only needs small input and produces small output, can be handled on the terminal easily. But when it comes to giving a huge input and the output produced will also be huge, then files become necessary to use. File handling offers efficient ways of programming with huge input and output data. Moreover, you do not have to enter the same input again and again and you can save the output of the program for later use. Here, we will learn to read data from a file by using the fread() function.

What is the Fread Function in C++?

The fread function is provided by the cstdio.h library. The cstdio.h header file contains all the functions that can be used on file, i.e., read, write, etc. The fread() function is used with files to read a block of data from an input stream. It reads the array of count objects, each object of size byte from the input stream and stores it in the output stream specified by the pointer. The total bytes read by the fread function is size*count. It returns all the elements read successfully.

Syntax of Fread Function

The fread function takes four parameters: p, s, c, and st. The size_t is an unsigned integer type that defines the variable type. The ‘p’ parameter refers to the memory block of at least s*c count byte size converted to a void*. The ‘s’ parameter holds the size of each element to be read. The file stream, from which we are going to read the data, is indicated by the ‘st’ option. It returns the elements that are read successfully and in case of error, the return elements might be less than the count. The examples given below will illustrate the working of the fread function better.

Example 1:
In the first example of a fread article, we will create a text file on the desktop and write some data in it. The fread function will then be used to read the data from the file. See the code below:

#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main()
{
    FILE* f;
    char b[100];
    f = fopen("test.txt", "rb");  
    while (!feof(f))
    {
        fread(b, sizeof(b), 1, f);
        cout << b;
    }
    return 0;
}

Two header files, bits/stdc++.h, and cstdio are included in the program at the start. When writing a c++ program, the essential header files must be included so that their utilities can be used in the program.

For example, the cstdio carries all the standard functions that can work on files like read, write, and etc. Similarly, the bits/stdc++.h holds all the standard libraries. So, when you include this, you have included all the standard libraries of c++ in the program. The ‘using namespace std’ is a standard library that allows the user to use all the functions of the standard c++ library. Moving forward, the complete code is written in the main() function where all the execution and working happens.

The file pointer ‘f’ is defined with File* f statement which will point to the memory block. An array ‘b’ of size 100 and type char is defined to hold the size of the data that will be read from the stream.

The fopen() function opens the file and takes at least two arguments, the file name, and the mode of the file. It throws an error if the file does not exist yet, or cannot be found; or else just open the existing file. The file mode (read, write, append, and etc.) refers to the mode in which the file has to be opened. The file name refers to the file that needs to be read. Here, ‘rb’ mode is provided which indicates that the file should open in the binary format for reading. While opening the file, you need to provide the complete path of the file where it exists. For example, your file is present in the document so you must add the complete path to the documents like this: “C:\\Users\\<username>\\Document\\<filename>”.

Next, we defined a ‘while’ loop that iterates through each element in the file and terminates only when it finds the eof (end of file). In the ‘while’ loop the fread function is used and all four parameters are passed for reading from the file. The cout statement will print the data present in the file on the terminal.

Finally, the return 0 statement is used indicating: do not return anything in case of successful execution. Press the f11 button on the keyboard or click the execution icon on the dev c++ software toolbar to execute the program. Now, let us see the output below:

Example 2:
Let us demonstrate the working of the fread function when the file size is zero. See the code below:

#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main()
{
    FILE* f;
    char b[100];
    f = fopen("test.txt", "rb");
    cout<<"Size of the File = "<<fread(b, sizeof(b), 1, f);
    return 0;
}

Here is the output:

Example 3:
As we have seen some simple and easy examples, let us work with a complicated example. See the code below:

#include <cstdio>
enum { SIZE = 5 };
int main(void)
{
    double a[SIZE] = {10, 20, 50, 70, 100};
    FILE *f = fopen("C:\\Users\\”System Name” \\Desktop\\testing.bin", "wb");
    fwrite(a, sizeof *a, SIZE, f);
    fclose(f);
    double b[SIZE];
    f = fopen("C:\\Users\\”System Name” \\Desktop\\testing.bin","rb");
    size_t r = fread(b, sizeof *b, SIZE, f);
    if(r == SIZE) {
        puts("Array contents = ");
        for(int n = 0; n < SIZE; n++)
        printf("%f ", b[n]);
    }
    fclose(f);
}

Here, we declared an ‘enum’ so that the ‘size’ can be used more conveniently. By changing the value of one variable ‘size’, it changes in the complete program.

An array of type double is created containing the data that will be written in the file. fopen() function opens a binary file in write mode ‘wb’. If the binary file already exists, it opens it in write mode; otherwise, it creates a new file with the supplied filename. The fwrite() function is castoff to write the array content to a file. The fwrite() function takes the same parameters as fread() function. After writing the data in the file, the fclose() function is used to close the file so that no unnecessary or unintentional changes can be made in the file.

The rest of the fread function is the same as we used in previous examples. Let us see the result of this code:

As you can see the data of the array is successfully written in the file.

Conclusion

In this guide, we had an overview of fread() function. We learned how to use the fread function with files for reading the data. We gave the practical demonstration for three different ways to employ the fread function in C++ programming language.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.