C fread and feof
fread reports how many bytes it copied when the element size is one.
A simple example
fread and feof
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
fread(record, 1, sizeof record, input)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
#include <stdio.h>
int main(void) {
FILE *input = tmpfile();
if (!input) return 1;
unsigned char packet[] = {0, 5}, record[4];
if (fwrite(packet, 1, sizeof packet, input) != sizeof packet) {
fclose(input);
return 1;
}
rewind(input);
size_t count = fread(record, 1, sizeof record, input);
if (count < sizeof record && feof(input)) puts("Request the complete record");
int failed = ferror(input);
fclose(input);
if (failed) return 1;
return 0;
}
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
A short read can also indicate an I/O failure. Check feof and ferror before choosing a response.