file-handling · beginner · ~10 min

Get a file's size

Measure a file with fseek/ftell.

Challenge

Your job

long file_size(const char *path);

Return the size of path in bytes using fseek/ftell, or -1 on NULL or open failure.

Hints

  1. fseek(f, 0, SEEK_END) then ftell(f).
  2. Open in binary mode for an accurate byte count.

Why this matters

Seeking to the end and asking 'where am I?' is the classic stdio way to size a file before reading it.

Starter code

#include <stdio.h>
long file_size(const char *path) {
    /* TODO */
    (void)path;
    return -1;
}

Common mistakes

Text mode on some platforms skews the count. Not handling fseek/ftell failure. Leaking the handle.

Edge cases to handle

Empty file → 0. Missing → -1.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.