File Handling · intermediate · ~10 min

fread for binary I/O

Read fixed-size records or raw bytes.

Lesson

size_t fread(void *buf, size_t sz, size_t n, FILE *f) reads up to n items of sz bytes each. Returns the number of items actually read (less than n on EOF or error). Distinguish EOF from error with feof / ferror.

For text line-by-line, use fgets; fread is for binary or known-size records.

Code examples

unsigned char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) {
    process(buf, n);
}
if (ferror(f)) perror("read");

Common mistakes

  • Using fread's return value as bytes — it's items, byte count is n * sz.