dirname Subroutine

Purpose

Report the parent directory name of a file path name.

Library

Standard C Library (libc.a)

Syntax

#include <libgen.h>

char *dirname (path) char *path

Description

Given a pointer to a character string that contains a file system path name, the dirname subroutine returns a pointer to a string that is the parent directory of that file. Trailing "/" characters in the path are not counted as part of the path.

If path is a null pointer or points to an empty string, a pointer to a static constant "." is returned.

The dirname and basename subroutines together yield a complete path name. dirname (path) is the directory where basename (path) is found.

Parameters

Item Description
path Character string containing a file system path name.

Return Values

The dirname subroutine returns a pointer to a string that is the parent directory of path. If path or *path is a null pointer or points to an empty string, a pointer to a string "." is returned. The dirname subroutine may modify the string pointed to by path and may return a pointer to static storage that may then be overwritten by sequent calls to the dirname subroutine.

Examples

A simple file name and the strings "." and ".." all have "." as their return value.

Input string Output string
/usr/lib /usr
/usr/ /
usr .
/ /
. .
.. .

The following code reads a path name, changes directory to the appropriate directory, and opens the file.

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