file-handling · beginner · ~10 min
Measure a file with fseek/ftell.
long file_size(const char *path);
Return the size of path in bytes using fseek/ftell, or -1 on NULL or
open failure.
fseek(f, 0, SEEK_END) then ftell(f).Seeking to the end and asking 'where am I?' is the classic stdio way to size a file before reading it.
#include <stdio.h>
long file_size(const char *path) {
/* TODO */
(void)path;
return -1;
}
Text mode on some platforms skews the count. Not handling fseek/ftell failure. Leaking the handle.
Empty file → 0. Missing → -1.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.