file-handling · intermediate · ~15 min

File size via stat

Query file metadata without opening the file.

Challenge

Get a file's size from its metadata, without opening the file.

Task

Implement long stat_size(const char *path) that returns the size in bytes of the file at path, using stat() and its st_size field.

Input

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

Output

Return the file size in bytes, or -1 if stat fails (e.g. the file doesn't exist).

Example

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

Edge cases

  • Missing file (stat fails): -1.

Rules

  • Use struct stat + stat(path, &st); read st.st_size. Do not open the file.

Input format

path: file to measure.

Output format

long size from st_size, or -1 if stat fails.

Constraints

Use stat(); do not open the file.

Starter code

#include <sys/stat.h>

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

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