🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fread in C Explained
Learn to read records with fread(), handle end of file and errors correctly, and see why random access matters.
In this free C programming course lecture you learn fread in C, the partner of fwrite(). It rebuilds structures and arrays from a binary file, which is what embedded C programming projects do when they reload logs, calibration tables and settings. You will read a record file in a safe loop, tell end of file from a read error, catch a damaged file with one extra check, and see why jumping directly to a record is faster than reading everything before it.
What You Will Learn
- How fread() uses ptr, size, nmemb and stream
- The correct loop for reading records until end of file
- How feof() and ferror() explain a short read
- How to detect a truncated or damaged file
- Why random access exists and how record offsets are computed
Prerequisites
- fwrite lecture (cp11_20) and the log.bin file it creates
- Shared structure header ep_records.h
- Basic shell commands such as cp and truncate
How fread in C Works
fread() is the mirror of fwrite(). It copies up to size * nmemb bytes from the stream into the memory you supply and returns how many whole items it filled. The buffer must be at least that large, because fread() cannot check it.
Reading Records Until End of File
This reader loads the file produced in the previous lecture. The loop ends the moment fread() delivers less than one record.
#include <stdio.h>
#include "ep_records.h"
int main(void)
{
struct log_rec r;
FILE *fp = fopen("log.bin", "rb");
size_t got;
int count = 0;
if (fp == NULL) {
perror("log.bin");
return 1;
}
printf("%-4s %-8s %-5s\n", "SEQ", "TEMP(C)", "ADC");
while ((got = fread(&r, sizeof r, 1, fp)) == 1) {
printf("%-4u %-8.1f %-5u\n", (unsigned)r.seq, r.temp_c10 / 10.0, (unsigned)r.adc);
count++;
}
if (ferror(fp))
perror("fread");
else if (feof(fp))
printf("-- end of file after %d records --\n", count);
fclose(fp);
return 0;
}gcc -Wall -Wextra -std=c11 -o ep_rec_read ep_rec_read.c
./ep_rec_readSEQ TEMP(C) ADC
1 24.5 1020
2 24.7 1031
3 25.1 1044
4 24.9 1038
5 25.6 1060
-- end of file after 5 records --Note: Header file ep_records.h is the same one used when writing. Sharing one header guarantees the writer and the reader agree on the layout.
Return Value, feof and ferror
A short result has two possible causes, and the stream flags tell them apart.
| Result of fread | feof(fp) | ferror(fp) | Meaning |
|---|---|---|---|
| Equal to nmemb | 0 | 0 | Everything was read |
| Less than nmemb | Non-zero | 0 | Reached the end of the file |
| Less than nmemb | 0 | Non-zero | A read error occurred |
#include <stdio.h>
#include "ep_records.h"
int main(int argc, char *argv[])
{
struct log_rec buf[10];
FILE *fp;
size_t got;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "rb");
if (fp == NULL) {
perror(argv[1]);
return 1;
}
got = fread(buf, sizeof buf[0], 10, fp);
printf("asked 10 records, got %zu\n", got);
printf("feof=%d ferror=%d\n", feof(fp) != 0, ferror(fp) != 0);
fclose(fp);
return 0;
}Run it against the good file, against a copy truncated to 27 bytes, and against a file that does not exist:
gcc -Wall -Wextra -std=c11 -o ep_fread_short ep_fread_short.c
cp log.bin cut.bin && truncate -s 27 cut.bin
./ep_fread_short log.bin
./ep_fread_short cut.bin
./ep_fread_short nothere.binasked 10 records, got 5
feof=1 ferror=0
asked 10 records, got 3
feof=1 ferror=0
nothere.bin: No such file or directoryThe truncated file holds 3 full records and 3 stray bytes. fread() returns 3 and says nothing about the stray bytes, so a damaged tail can go unnoticed.
Catching a Damaged Record
Reading with an item size of 1 byte reveals the truth, because the byte count then exposes the partial record.
#include <stdio.h>
#include "ep_records.h"
int main(void)
{
struct log_rec buf[5];
FILE *fp = fopen("cut.bin", "rb");
size_t a;
if (fp == NULL) { perror("cut.bin"); return 1; }
a = fread(buf, sizeof buf[0], 5, fp);
printf("item size 8 : returned %zu\n", a);
rewind(fp);
a = fread(buf, 1, sizeof buf, fp);
printf("item size 1 : returned %zu bytes\n", a);
fclose(fp);
return 0;
}item size 8 : returned 3
item size 1 : returned 27 bytes27 bytes is not a multiple of 8, so the file is damaged. In real code, compute bytes % sizeof(struct log_rec) and reject the file when the remainder is not zero.
Sequential Access vs Random Access
Every loop so far reads sequentially: to see record 44 you first read records 1 to 43. That is fine for a few hundred bytes, but wasteful for a large log. Random access jumps straight to a position computed from the record size.
| Record number | Byte offset for 8-byte records |
|---|---|
| 1 | 0 |
| 2 | 8 |
| 44 | 344 |
The formula is offset = (record number minus 1) times record size. C provides fseek() to move the file position to that offset before calling fread() or fwrite(). The upcoming lecture covers it in full.
Common fread Mistakes and Best Practices
| Mistake | Result | Fix |
|---|---|---|
| while(!feof(fp)) loop | One extra bogus record | Loop on the fread() return value |
| Buffer smaller than size x nmemb | Memory corruption | Size the buffer from sizeof and the count |
| Using data after a short read | Stale or garbage values | Use only the returned item count |
| Reader and writer use different structures | Wrong values with no error | Share one header |
| Ignoring ferror() | I/O faults look like clean EOF | Check ferror() after a short read |
- Zero-initialise buffers so unread fields are predictable.
- Validate everything you read from a file before trusting it, especially counts used as loop bounds or array indices.
- Read many records per call to cut system-call overhead.
Summary and Key Takeaways
- fread() returns the number of whole items read, which can be less than requested.
- Loop on the fread() return value, never on feof() alone.
- A short count with feof set means end of file, with ferror set means a read error.
- Read with a 1-byte item size to spot partial records.
- Random access uses offset = (record number minus 1) times record size and is covered next.
Conclusion
You can now write records and read them back safely, and you know the limits of sequential reading. Sequential access reads everything before the record you want, so the next topic of this free embedded C course, random access with fseek(), is a big step. One final lecture first: a hands-on configuration store, a look at structure padding, and the chapter quiz.
Frequently Asked Questions
What does fread return when the file ends?
It returns the number of whole items it managed to read, which may be less than requested, including 0. A short count means end of file or an error, so call feof() and ferror() to tell which.
Why shouldn’t I use while(!feof(fp)) for reading?
The end-of-file flag is set only after a read attempt hits the end. The loop therefore runs one extra time and processes stale data. Loop on the fread() return value instead.
How can I detect a file with a partial last record?
Read with an item size of 1 byte and check that the byte count is a multiple of the record size, or compare the file size with a whole number of records.
Can fread read into a larger array than the file holds?
Yes. It stops at the end of the file and returns how many items it filled. Only use that many elements afterwards.
Does fread care about the type of the buffer?
No. It copies bytes. If the buffer type does not match the type that was written, the values will be wrong even though no error is reported.
What is random access in C file handling?
It means jumping directly to a byte offset such as record 44 without reading the 43 records before it. C provides fseek() for that, which is the next topic in this chapter.
Keep Going with Free C Tutorials
Next up: a binary configuration store lab, padding pitfalls, quiz and interview questions.

2 Comments