file-handling · beginner · ~10 min

Get a file's size

Measure a file with fseek/ftell.

Challenge

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.

Task

Implement long file_size(const char *path) that returns the number of bytes in the file at path, using fseek and ftell.

Input

path: filename of a file the grader writes in the working directory.

Output

Return the file size in bytes. Return -1 if path is NULL or the file can't be opened.

Example

file "fs.bin" = 10 bytes   ->   file_size("fs.bin") == 10
empty file                 ->   0
missing file               ->   -1

Edge cases

  • Empty file: 0.
  • Missing file or NULL path: -1.

Rules

  • Open in binary mode for an exact byte count; fseek to SEEK_END, then ftell; close before returning.

Why this matters

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

Input format

path: file to measure.

Output format

long size in bytes, or -1 on NULL path / open failure.

Constraints

Use fseek(SEEK_END)+ftell in binary mode; handle fseek/ftell failure.

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.