Updated: May 06, 2022

Find the parent directory part of a file pathname


#include <libgen.h>

char *dirname( char *path );


The string to parse.



Use the -l c option to qcc to link against this library. This library is usually included automatically.


The dirname() function takes a pointer to a character string that contains a pathname, and returns a pointer to a string that's a pathname of the parent directory of that file. Trailing / characters in the path aren't counted as part of the path.

If the path doesn't contain a / character, or path is a NULL pointer or points to an empty string, then dirname() function returns a pointer to the string "." (dot).

Together the dirname() and basename() functions yield a complete pathname. The expression dirname(path) obtains the pathname of the directory where basename(path) is found.

Note: The dirname() function might modify the string pointed to by path, and can return a pointer to static storage.


A pointer to a string that's the parent directory of path. If path is a NULL pointer or points to an empty string, a pointer to a string "." is returned.


String input String output
/usr/lib /usr
/usr/ /
/ /
. .
.. .

The following code fragment reads a pathname, changes the current working directory to the parent directory, and opens the file:

char path[BUFF_SIZE], *pathcopy;
int fd;

fgets(path, BUFF_SIZE, stdin);
pathcopy = strdup(path);
fd = open(basename(path), O_RDONLY);


POSIX 1003.1

Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes