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.
C++
// C program to use the fread() function to read the content of binary file into an array.
#include <stdio.h>
int main() {
FILE *file;
int buffer[5];
// Open the binary file for reading
file = fopen("input.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Read the integers from the file into the buffer
fread(buffer, sizeof(int),5, file);
// Print the integers that were read
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, buffer[i]);
}
// Close the file
fclose(file);
return 0;
}
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.
C
// C program to illustrate fread() function
#include <stdio.h>
int main(){
// File pointer
FILE *filePointer;
// Buffer to store the read data
char buffer[100];
size_t bytesRead;
// "Gfg.txt" file is opened in read mode
filePointer = fopen("Gfg.txt", "r");
// Ensure the file was opened successfully
if (!filePointer){
printf("Error opening file.\n");
return 1;
}
// Data is read from the file into the buffer
while ((bytesRead = fread(buffer, 1, sizeof(buffer) - 1, filePointer)) > 0){
// Null-terminate the buffer
buffer[bytesRead] = '\0';
// Print the read data
printf("%s", buffer);
}
fclose(filePointer);
return 0;
}
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.
C
// C program to illustrate fread() function
// when size of the file or the value of count is equal to 0
#include <stdio.h>
int main()
{
// File pointer
FILE* filePointer;
// Buffer to store the read data
char buffer[100];
// "g4g.txt" file is opened in read mode
filePointer = fopen("g4g.txt", "r");
// Case when count is equal to 0
printf("count = 0, return value = %zu\n",
fread(buffer, sizeof(buffer), 0, filePointer));
// Case when size is equal to 0
printf("size = 0, return value = %zu\n",
fread(buffer, 0, 1, filePointer));
return 0;
}
Outputcount = 0, return value = 0
size = 0, return value = 0
Similar Reads
Basics of File Handling in C File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.Need of File Han
13 min read
C fopen() Function In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
5 min read
EOF, getc() and feof() in C In this article, we will discuss the EOF, getc() function and feof() function in C.What is EOF?In C, EOF is a constant macro defined in the <stdlib.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets()
3 min read
fgets() in C In C, fgets() is a built-in function defined in <stdio.h> header file. It reads the given number of characters of a line from the input stream and stores it into the specified string. This function stops reading the characters when it encounters a newline character, has read the given number o
3 min read
fprintf() in C fprintf is used to print content in file instead of stdout console. int fprintf(FILE *fptr, const char *str, ...); Example: C // C Program for the above approach #include<stdio.h> int main() { int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("sample.txt
1 min read
scanf() and fscanf() in C In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of characters written in it otherwise, returns a negative value.Syntax:int scanf(const char *characters_set)Time Complexity: O(n)Auxiliary Space: O(n) where n is the length of input.Many of us kno
4 min read
C fread() Function 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 f
4 min read
fseek() vs rewind() in C In C, the functions fseek() and rewind() helps in manipulating the position of the pointer in the opened file but serve different purposes and have distinct working. The below table lists the major differences between fseek() and rewind() in C:Featurefseek()rewind()FunctionalityMoves the file pointe
2 min read
What is return type of getchar(), fgetc() and getc() ? In C, getchar(), fgetc(), and getc() all are the functions used for reading characters from input buffer. This buffer is standard input buffer for getchar() and can be any specified file for getc() and fgetc(). In this article, we will learn about the return type of these functions and why it matter
3 min read
Read/Write Structure From/to a File in C For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data.Writing Structure to a File using fwriteWe can use fwr
3 min read