file-handling · beginner · ~10 min
Measure a file with fseek/ftell.
Find a file's size in bytes by seeking to the end and asking "where am I?" — the classic stdio way to measure a file before reading it.
Implement long file_size(const char *path) that returns the number of bytes in the file at path, using fseek and ftell.
path: filename of a file the grader writes in the working directory.
Return the file size in bytes. Return -1 if path is NULL or the file can't be opened.
file "fs.bin" = 10 bytes -> file_size("fs.bin") == 10
empty file -> 0
missing file -> -1
fseek to SEEK_END, then ftell; close before returning.Seeking to the end and asking 'where am I?' is the classic stdio way to size a file before reading it.
path: file to measure.
long size in bytes, or -1 on NULL path / open failure.
Use fseek(SEEK_END)+ftell in binary mode; handle fseek/ftell failure.
#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.