file-handling · beginner · ~10 min
Find the last separator and copy the tail safely.
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.
"/a/b/file.txt" → "file.txt""plain.c" → "plain.c"/ with a reverse scan (or strrchr).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().
#include <stddef.h>
int basename_of(const char *path, char *out, size_t cap) {
/* TODO */
(void)path; (void)out; (void)cap;
return -1;
}
Including the slash. Mishandling a trailing slash. No overflow guard.
No slash. Trailing slash → empty string. Tiny buffer.
O(path length).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.