dirname

Reports the parent directory name of a file path name.

Format

#include  <libgen.h>

char *dirname  (char *path);
Function Variants This function also has variants named _dirname32 and _dirname64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions.

Argument

path
The file path name.

Description

This function takes a pointer to a character string that contains a UNIX path name and returns a pointer to a string that is a path name of the parent directory of that file. Trailing '/' (slash) characters in the path are not counted as part of the path.

The dirname function returns a pointer to the string "." (dot), when the path argument:

The dirname function can modify the string pointed to by the path argument.

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

See also basename in this section.

Return Values
A pointer to a string that is the parent directory of the path argument. 
"."  The path argument:

  • Does not contain a '/' (slash).

  • Is a NULL pointer.

  • Points to an empty string.
 

Example

    Using the dirname function, the following example reads a path name, changes the current working directory to the parent directory, and opens a file.

        char path [MAXPATHLEN], *pathcopy;
        int fd;
        fgets(path, MAXPATHLEN, stdin);
        pathcopy = strdup(path);
        chdir(dirname(pathcopy));
        fd = open(basename(path), O_RDONLY);
    


Previous Page | Next Page | Table of Contents | Index