How to Use fread in C: Syntax, Example, and Tips
In C,
fread reads binary data from a file into a buffer. You call it with a pointer to the buffer, size of each item, number of items to read, and the file pointer. It returns the number of items successfully read.Syntax
The fread function reads data from a file into memory. Its syntax is:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
- ptr: Pointer to the memory buffer where data will be stored.
- size: Size in bytes of each item to read.
- count: Number of items to read.
- stream: Pointer to the open file to read from.
The function returns the number of items successfully read, which can be less than count if end of file or error occurs.
c
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);Example
This example opens a file named example.bin, reads 5 integers from it using fread, and prints them.
c
#include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("example.bin", "rb"); if (!file) { perror("Failed to open file"); return 1; } int numbers[5]; size_t items_read = fread(numbers, sizeof(int), 5, file); if (items_read != 5) { if (feof(file)) { printf("Reached end of file after reading %zu items.\n", items_read); } else if (ferror(file)) { perror("Error reading file"); } } fclose(file); printf("Numbers read from file:\n"); for (size_t i = 0; i < items_read; i++) { printf("%d\n", numbers[i]); } return 0; }
Output
Numbers read from file:
10
20
30
40
50
Common Pitfalls
- Not opening the file in binary mode (
"rb") when reading binary data can cause incorrect results on some systems. - Ignoring the return value of
freadcan lead to using uninitialized data if fewer items are read. - Using
sizeofincorrectly for the item size can cause reading wrong amounts of data. - Not checking for end-of-file or errors after reading can cause bugs.
Always check the return value and handle errors or end-of-file properly.
c
#include <stdio.h> int main() { FILE *file = fopen("data.bin", "r"); // Wrong: should be "rb" if (!file) return 1; int buffer[3]; size_t read = fread(buffer, sizeof(int), 3, file); // Corrected: size and count fixed if (read != 3) { // Error handling missing } fclose(file); return 0; } // Correct usage: // FILE *file = fopen("data.bin", "rb"); // size_t read = fread(buffer, sizeof(int), 3, file);
Quick Reference
- fread(ptr, size, count, stream): Reads
countitems ofsizebytes intoptrfromstream. - Returns number of items read, which may be less than
countif EOF or error. - Open files in binary mode (
"rb") for binary reading. - Check return value to avoid using incomplete data.
Key Takeaways
Use fread to read binary data by specifying buffer, item size, count, and file pointer.
Always open files in binary mode ("rb") when reading binary data.
Check the return value of fread to know how many items were actually read.
Handle end-of-file and errors after fread to avoid bugs.
Use sizeof correctly to specify the size of each item to read.