![]() |
VOOZH | about |
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.
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.
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.
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.
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
This C program demonstrates the usage of the fread() function when the file's size or count is equal to 0.
count = 0, return value = 0 size = 0, return value = 0