Lesson 18 of 23

basename

The basename Command

basename strips the directory prefix from a path, leaving just the filename:

$ basename /usr/bin/ls
ls
$ basename ./src/main.c
main.c

Everything up to and including the last / is discarded.

Your Implementation

Write void my_basename(const char *path) that prints the filename component.

The algorithm: scan the entire string tracking the position right after the last /. At the end, print from that position.

void my_basename(const char *path) {
    const char *last = path;
    for (const char *p = path; *p; p++)
        if (*p == '/') last = p + 1;
    printf("%s\n", last);
}

Start last pointing at the beginning of the string. Each time a / is found, advance last to the character after it. When the loop ends, last points at the start of the final component.

Edge Cases

  • /usr/bin/lsls (normal case)
  • lsls (no slash — the whole string is the basename)
  • / → empty string (trailing slash after root — real basename returns /, but we keep it simple)

Your Task

Implement my_basename that prints the last path component.

TCC compiler loading...
Loading...
Click "Run" to execute your code.