C fread
Created By: chatGPT
The
Parameters of fread
function in C is used to read binary data from a file. This function is particularly useful when you need to read a large amount of binary data, such as an array or a structure. The function prototype is as follows:size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
fread
:ptr
: A pointer to a block of memory where the read data should be stored.size
: The size in bytes of each element to be read.count
: The number of elements to be read.stream
: The pointer to aFILE
object that specifies an input stream.
fread
is the number of elements successfully read, which may be less than count
if an error or end-of-file occurs. To check for such conditions, it's important to also utilize feof
and ferror
functions.Here’s an example demonstrating how to use
fread
to read data from a binary file into an array:#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
int buffer[10];
size_t result;
// Open the file in binary mode for reading
file = fopen("data.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// Read data into buffer
result = fread(buffer, sizeof(int), 10, file);
if (result != 10) {
if (feof(file)) {
printf("Reached end of file after reading %zu elements.\n", result);
}
if (ferror(file)) {
perror("Error reading file");
}
}
// Close the file
fclose(file);
// Print the read elements
for (size_t i = 0; i < result; i++) {
printf("Element %zu: %d\n", i, buffer[i]);
}
return EXIT_SUCCESS;
}
In this example:
- A file called
data.bin
is opened in binary read mode. fread
reads up to 10 integers into the arraybuffer
.- After reading, it checks whether the read was successful and handles either end-of-file or error conditions accordingly.
- Finally, it prints the elements of the read array.