VOOZH about

URL: https://www.geeksforgeeks.org/c/fread-function-in-c/

⇱ C fread() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C fread() Function

Last Updated : 17 Sep, 2024

The C fread() is a standard library function used to read the given amount of data from a file stream. Defined inside <stdio.h>, the fread() function reads the given number of elements of specific size from the file stream and stores it in the buffer memory. The total number of bytes read by fread() function is the number of elements read multiplied by the size of each element in bytes.

Syntax of C fread()

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

The file position indicator is automatically moved forward by the number of bytes read. If the objects being read are not trivially copy-able, such as structures or complex data types then it does not behave properly.

Parameters

  • buffer: It refers to the pointer to the buffer memory block where the data read will be stored.
  • size: It refers to the size of each element in bytes.
  • count: It refers to the count of elements to be read.
  • stream: It refers to the pointer to the file stream.

Return Value

  • The function returns the number of elements that are read successfully from the file.
  • If the return value is less than the count, it means that an error occurred or it has reached the end of the file.
  • If the value of size or count is zero, fread() returns zero and performs no other action.

Note: fread() function itself does not provide a way to distinguish between end-of-file and error, feof and ferror can be used to determine which occurred.

Examples of C fread()

Example 1

The below programs illustrate the fread() function.


Output

Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

Here, input.bin file should contain the binary representation of the integers: 10, 20, 30, 40, 50.

Example 2

The below programs demonstrates the use of the fread() function to read data from a file and store it in a buffer.


Suppose the file Gfg.txt contains the following data:

Geeks : DS-ALgo 
Gfg : DP
Contribute : writearticle

Then, after running the program, the output will be

Geeks : DS-ALgo 
Gfg : DP
Contribute : writearticle

Example 3

This C program demonstrates the usage of the fread() function when the file's size or count is equal to 0.


Output
count = 0, return value = 0
size = 0, return value = 0
Comment