fread() Function in C

The syntax of fread() function is this:

fread() function is the complementary of fwrite() function. fread() function is commonly used to read binary data. It accepts the same arguments as fwrite() function does.

Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

The ptr is the starting address of the memory block where data will be stored after reading from the file. The function reads n items from the file where each item occupies the number of bytes specified in the second argument. On success, it reads n items from the file and returns n. On error or end of the file, it returns a number less than n.

Let’s take some examples:

Example 1: Reading a float value from the file

This reads a float value from the file and stores it in the variable val.

Example 2: Reading an array from the file

This reads an array of 10 integers from the file and stores it in the variable arr.

Example 3: Reading the first 5 elements of an array

This reads 5 integers from the file and stores it in the variable arr.

Example 4: Reading the first 5 elements of an array

This reads 5 integers from the file and stores it in the variable arr.

Example 5: Reading the structure variable

This reads the contents of a structure variable from the file and stores it in the variable student_1.

Example 6: Reading an array of structure

This reads first 10 elements of type struct student from the file and stores them in the variable arr_student.

The following program demonstrates how we can use fread() function.

Expected Output:

How it works:

In lines 4-10, a structure employee is declared along with a variable emp . The structure employee has four members namely: name, designation, age and salary.

In line 14, a structure pointer fp of type struct FILE is declared.

In line 15, fopen() function is called with two arguments namely "employee.txt" and "rb". On success, it returns a pointer to file employee.txt and opens the file employee.txt in read-only mode. On failure, it returns NULL.

In lines 17-21, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In lines 25-31, a while loop is used along with fread() to read the contents of the file. The fread() function reads the records stored in the file one by one and stores it in the structure variable emp. The fread() function will keep returning 1 until there are records in the file. As soon as the end of the file is encountered fread() will return a value less than 1 and the condition in the while loop become false and the control comes out of the while loop.

In line 33, fclose() function is used to close the file.

2 thoughts on “fread() Function in C

  1. In the first example, while storing 4 bytes in integer variable, sequence of bytes is getting reversed. (i.e. 09 A4 35 0E is stored as 0E 35 A4 09)

Leave a Comment