file-handling · beginner · ~10 min

Extract the final path component

Find the last separator and copy the tail safely.

Challenge

Your job

int basename_of(const char *path, char *out, size_t cap);

Copy the part of path after the last / into out (NUL-terminated). A path with no / is its own basename. Return bytes written, or -1 on NULL/overflow.

Examples

  • "/a/b/file.txt""file.txt"
  • "plain.c""plain.c"

Hints

  1. Find the last / with a reverse scan (or strrchr).
  2. Copy everything after it.

Why this matters

Pulling the filename out of a path is a constant chore — and doing it by hand avoids the surprising in-place behaviour of libc basename().

Starter code

#include <stddef.h>
int basename_of(const char *path, char *out, size_t cap) {
    /* TODO */
    (void)path; (void)out; (void)cap;
    return -1;
}

Common mistakes

Including the slash. Mishandling a trailing slash. No overflow guard.

Edge cases to handle

No slash. Trailing slash → empty string. Tiny buffer.

Complexity

O(path length).

Background lessons

Up next

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