Reports the parent directory name of a file pathname. Format #include <libgen.h> char *dirname (char *path);
1 – Function Variants
The dirname function has variants named _dirname32 and _dirname64 for use with 32-bit and 64-bit pointer sizes, respectively.
2 – Argument
path The file pathname.
3 – Description
The dirname function takes a pointer to a character string that contains a UNIX pathname and returns a pointer to a string that is a pathname of the parent directory of that file. Trailing slash (/) characters in the path are not counted as part of the path. This function returns a pointer to the string "." (dot), when the path argument: o Does not contain a slash (/). o Is a NULL pointer. o Points to an empty string. The dirname function can modify the string pointed to by the path argument. The dirname and basename functions together yield a complete pathname. The expression dirname(path) obtains the pathname of the directory where basename(path) is found. See also basename.
4 – Return Values
x A pointer to a string that is the parent directory of the path argument. "." The path argument: o Does not contain a slash (/). o Is a NULL pointer. o Points to an empty string.
5 – Example
Using the dirname function, the following example reads a pathname, 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);