How to Read Binary File in C: Syntax and Example
To read a binary file in C, use
fopen with mode "rb" to open the file, then use fread to read data into a buffer, and finally close the file with fclose. This method reads raw bytes exactly as stored in the file.Syntax
Here is the basic syntax to read a binary file in C:
FILE *file = fopen("filename", "rb");opens the file in binary read mode.fread(buffer, size, count, file);readscountitems ofsizebytes intobuffer.fclose(file);closes the file when done.
c
FILE *file = fopen("filename", "rb"); if (file == NULL) { // handle error } size_t itemsRead = fread(buffer, size, count, file); fclose(file);
Example
This example reads 10 integers from a binary file named data.bin and prints them.
c
#include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("data.bin", "rb"); if (file == NULL) { perror("Failed to open file"); return 1; } int numbers[10]; size_t itemsRead = fread(numbers, sizeof(int), 10, file); if (itemsRead != 10) { printf("Warning: Expected 10 integers but read %zu\n", itemsRead); } fclose(file); for (size_t i = 0; i < itemsRead; i++) { printf("Number %zu: %d\n", i + 1, numbers[i]); } return 0; }
Output
Number 1: 12
Number 2: 34
Number 3: 56
Number 4: 78
Number 5: 90
Number 6: 123
Number 7: 456
Number 8: 789
Number 9: 1011
Number 10: 1213
Common Pitfalls
Common mistakes when reading binary files include:
- Not opening the file in binary mode (
"rb"), which can cause data corruption on some systems. - Ignoring the return value of
fread, which tells how many items were actually read. - Reading more data than the buffer can hold, causing memory errors.
- Not checking if
fopensucceeded before reading.
c
/* Wrong way: opening file in text mode */ FILE *file = fopen("data.bin", "r"); // Should be "rb" /* Right way: */ FILE *file = fopen("data.bin", "rb"); if (file == NULL) { // handle error } size_t readCount = fread(buffer, size, count, file); if (readCount != count) { // handle partial read } fclose(file);
Quick Reference
Tips for reading binary files in C:
- Always use
"rb"mode withfopento avoid data issues. - Use
freadto read raw bytes into a buffer. - Check the return value of
freadto know how many items were read. - Close the file with
fcloseto free resources.
Key Takeaways
Open binary files with fopen using mode "rb" to read raw bytes safely.
Use fread to read data into a buffer and always check how many items were read.
Always verify fopen succeeded before reading to avoid crashes.
Close files with fclose to release system resources.
Avoid reading more data than your buffer can hold to prevent memory errors.