C fread() Function

beginner
12 min

C fread() Function

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!

Understanding fread()

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.

Syntax and Parameters

Here's the basic syntax for the fread() function:

c
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.

Example 1: Reading an Entire Text File

To read an entire text file into a single string, you can use fread() as follows:

c
#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.

Example 2: Reading Structures

fread() can also be used to read structures from a file, making it an ideal choice for working with structured data files like CSVs.

c
#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.

Quiz

Quick Quiz
Question 1 of 1

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! šŸŽÆ