Lesson 19 of 23

dirname

The dirname Command

dirname is the complement of basename — it prints everything except the last path component:

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

Your Implementation

Write void my_dirname(const char *path) that prints the directory component.

There are three cases to handle:

  1. No slash in path → print . (the current directory)
  2. Slash is the first character only → print / (root)
  3. Otherwise → print everything up to (but not including) the last /
void my_dirname(const char *path) {
    int len = 0;
    while (path[len]) len++;

    // Find last slash
    int last = -1;
    for (int i = 0; i < len; i++)
        if (path[i] == '/') last = i;

    if (last == -1) {
        printf(".\n");          // no slash → current dir
    } else if (last == 0) {
        printf("/\n");          // leading slash only → root
    } else {
        for (int i = 0; i < last; i++) putchar(path[i]);
        putchar('\n');
    }
}

Why Three Cases?

  • ls has no slash → dirname returns . by POSIX convention
  • /ls has a slash only at position 0 → the directory is / itself
  • /usr/bin/ls → last slash is at index 8 → print chars 0–7: /usr/bin

Your Task

Implement my_dirname that prints the directory portion of a path.

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