fread() Function
The fread()
function in C reads a block of data from a given stream into a specified memory block. It is commonly used for reading binary data from files, allowing you to specify both the size of each element and the number of elements to read. The function advances the stream’s position indicator by the total number of bytes read.
Syntax of fread()
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
Parameters
Parameter | Description |
---|---|
ptr | Pointer to a memory block with a size of at least (size * count ) bytes where the read data will be stored. |
size | The size, in bytes, of each element to be read. |
count | The number of elements, each of size size , to be read. |
stream | Pointer to a FILE object that specifies the input stream to read from. |
It is important to note that if either size
or count
is zero, fread()
returns zero without modifying the stream or the content of the memory pointed to by ptr
.
Return Value
The function returns the total number of elements successfully read. If this number differs from the count
parameter, it indicates that either a reading error occurred or the end-of-file was reached. The indicators for these situations can be checked using ferror()
and feof()
, respectively.
Examples for fread()
Example 1: Reading a Binary File into a Buffer
This example demonstrates how to open a binary file and use fread()
to read its contents into a buffer.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("data.bin", "rb");
if (fp == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// Allocate buffer for 100 integers
int buffer[100];
size_t elementsRead = fread(buffer, sizeof(int), 100, fp);
printf("Number of elements read: %zu\n", elementsRead);
fclose(fp);
return 0;
}
Explanation:
- The file
data.bin
is opened in binary read mode. - A buffer for 100 integers is allocated.
fread()
reads up to 100 integers from the file into the buffer.- The program prints the number of elements successfully read.
- The file is then closed.
Program Output:
Number of elements read: 100
Example 2: Reading a Text File into a Character Array
This example shows how to read contents from a text file into a character array using fread()
.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("text.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
char buffer[256];
size_t elementsRead = fread(buffer, sizeof(char), 255, fp);
buffer[elementsRead] = '\0'; // Null terminate the string
printf("File content:\n%s\n", buffer);
fclose(fp);
return 0;
}
Explanation:
- The file
text.txt
is opened in read mode. - A character array
buffer
is allocated to hold up to 255 characters. fread()
reads characters from the file into the buffer.- A null terminator is added to the end of the read content to form a proper C string.
- The file content is printed to the console.
- The file is closed after reading.
Program Output:
File content:
[Content of text.txt]
Example 3: Handling End-of-File and Read Errors
This example illustrates how to handle situations where fewer elements are read than expected, indicating either an error or the end-of-file.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("data.bin", "rb");
if (fp == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
int buffer[50];
size_t elementsRead = fread(buffer, sizeof(int), 50, fp);
if (elementsRead != 50) {
if (feof(fp)) {
printf("End-of-file reached after reading %zu elements.\n", elementsRead);
} else if (ferror(fp)) {
perror("Error reading file");
}
} else {
printf("Successfully read 50 elements.\n");
}
fclose(fp);
return 0;
}
Explanation:
- The file
data.bin
is opened in binary mode. - A buffer for 50 integers is allocated.
fread()
attempts to read 50 elements from the file.- If fewer than 50 elements are read, the program checks if the end-of-file was reached using
feof()
or if a read error occurred usingferror()
. - An appropriate message is printed based on the outcome.
- The file is closed after the operation.
Program Output:
End-of-file reached after reading [number] elements.