dirname()

Find the parent directory part of a file pathname

Synopsis:

#include <libgen.h>

char *dirname( char *path );

Arguments:

path
The string to parse.

Library:

libc

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

Description:

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.

Returns:

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.

Examples:

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);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);

Classification:

POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes