file-handling · intermediate · ~15 min

File size via fseek/ftell

Measure a file with fseek + ftell.

Challenge

Measure a file's size in bytes by seeking to its end.

Task

Implement long file_size(const char *path) that returns the size in bytes of the file at path, by seeking to the end and reading the position with ftell.

Input

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

Output

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

Example

file of 5 bytes   ->   5
missing file      ->   -1

Edge cases

  • Missing file: -1.

Rules

  • Open in binary mode; fseek to SEEK_END, then ftell.

Input format

path: file to measure.

Output format

long size in bytes, or -1 if it can't be opened.

Constraints

Seek to SEEK_END then ftell; open in binary mode.

Starter code

#include <stdio.h>

long file_size(const char *path) {
    /* TODO */
    return -1;
}

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