Understanding fread() Function in C: A Beginner’s Guide

Future Fanatic
2 min readMar 24, 2024

--

Introduction:

In the world of C programming, file handling is an essential aspect. One common task is reading data from files, which can be achieved using the fread() function. In this beginner’s guide, we’ll explore what fread() is, how it works, and how you can use it in your C programs.

What is fread()?

The fread() function in C is used to read data from a file. It stands for “file read” and is part of the C standard library (stdio.h). fread() reads a specified number of elements of a specific size from the given file stream and stores them in the provided buffer.

Syntax:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Parameters:

  • ptr: Pointer to the memory block where the data will be stored.
  • size: Size in bytes of each element to be read.
  • nmemb: Number of elements to read.
  • stream: Pointer to a FILE object that specifies the file stream to read from.

Return Value:

The fread() function returns the total number of elements successfully read, which may be less than nmemb if an error occurs or if the end of the file is reached.

Example:

#include <stdio.h>

int main() {
FILE *file;
char buffer[100];

// Open file in read mode
file = fopen("example.txt", "rb");

// Read 10 elements of size 1 byte from file to buffer
size_t elements_read = fread(buffer, 1, 10, file);

// Output the read data
printf("Read %zu elements: %s\n", elements_read, buffer);

// Close the file
fclose(file);

return 0;
}

Explanation:

  • We include the stdio.h header file for file handling functions.
  • In the main function, we declare a FILE pointer and a buffer to store the read data.
  • We open a file named “example.txt” in binary read mode (“rb”).
  • Using fread(), we read 10 elements of size 1 byte from the file into the buffer.
  • The number of elements successfully read is stored in the elements_read variable.
  • Finally, we print the read data along with the number of elements read.
  • The file is then closed using fclose().

Conclusion:

The fread() function in C provides a simple and efficient way to read data from files. By understanding its syntax and usage, you can incorporate file reading capabilities into your C programs with ease. Experiment with fread() in your projects to become more proficient in file handling tasks.

Remember, practice makes perfect! Happy coding!

--

--

Future Fanatic

Tech enthusiast, software, web, and game developer 🌐🎮 | Passionate about tech, art, writing, and endless creativity 🎨✍️ | Let's innovate and inspire! ✨