File Handling · intermediate · ~8 min

fwrite for binary output

Write raw bytes or fixed-size records.

Lesson

size_t fwrite(const void *buf, size_t sz, size_t n, FILE *f) is the write-side counterpart of fread. Returns the count of items successfully written. A write that returns less than n means an error — check ferror.

Flushing matters: data may sit in the user-space buffer until fclose, fflush, or buffer exhaustion. Long-running programs that need durability call fflush then fsync on the underlying file descriptor (fileno(f)).

Common mistakes

  • Forgetting to fflush before exit — buffered data is lost on crash.