Welcome to our comprehensive guide on the C fread() function! In this lesson, we'll dive deep into understanding what fread() is, why we use it, and how to implement it effectively in your C programs. Let's get started!
fread() is a powerful function in the C Standard Library that reads data from a file into memory. It offers an easy and efficient way to load files into your program, making it indispensable for working with data files in C.
š” Pro Tip: fread() is useful when you want to read a large amount of data at once, ensuring better performance compared to reading data one character at a time.
Here's the basic syntax for the fread() function:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);ptr: A pointer to the memory area where data is to be stored.size: The size of each element to be read (in bytes).nmemb: The number of elements to be read.stream: The file stream to be read.š Note: The function fread() returns the number of items successfully read, which could be less than nmemb if there isn't enough data in the file.
To read an entire text file into a single string, you can use fread() as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
char *data = malloc(fileSize + 1);
if (data == NULL) {
printf("Error: Unable to allocate memory.\n");
fclose(file);
return 1;
}
size_t bytesRead = fread(data, sizeof(char), fileSize, file);
data[bytesRead] = '\0';
fclose(file);
printf("File contents:\n%s\n", data);
free(data);
return 0;
}In this example, we're reading the entire content of example.txt into a single string and printing it to the console.
fread() can also be used to read structures from a file, making it an ideal choice for working with structured data files like CSVs.
#include <stdio.h>
typedef struct {
char name[32];
int age;
} Person;
int main() {
FILE *file = fopen("data.csv", "r");
if (file == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}
Person person;
while (fread(&person, sizeof(Person), 1, file) == 1) {
printf("Name: %s\nAge: %d\n", person.name, person.age);
}
fclose(file);
return 0;
}In this example, we're reading a CSV file containing name and age data, storing each entry in a Person structure, and printing it to the console.
What does the `fread()` function do in C programming?
Mastering the fread() function will help you work efficiently with data files in your C programs. Happy coding! šÆ