Directories and Links 371
z If pathname is a NULL pointer or an empty string, then both dirname() and
basename() return the string. (dot). (Concatenating these strings yields the
pathname ./., which is equivalent to ., the current directory.)
Table 18-3 shows the strings returned by dirname() and basename() for various example
pathnames.
Listing 18-5: Using dirname() and basename()
––––––––––––––––––––––––––––––––––––––––––––––––– dirs_links/t_dirbasename.c
#include <libgen.h>
#include "tlpi_hdr.h"
int
main(int argc, char argv[])
{
char t1, *t2;
int j;
for (j = 1; j < argc; j++) {
t1 = strdup(argv[j]);
if (t1 == NULL)
errExit("strdup");
t2 = strdup(argv[j]);
if (t2 == NULL)
errExit("strdup");
printf("%s ==> %s + %s\n", argv[j], dirname(t1), basename(t2));
free(t1);
free(t2);
}
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––– dirs_links/t_dirbasename.c
Table 18-3: Examples of strings returned by dirname() and basename()
Pathname string dirname() basename()
///
/usr/bin/zip /usr/bin zip
/etc/passwd//// /etc passwd
/etc////passwd /etc passwd
etc/passwd etc passwd
passwd. passwd
passwd/. passwd
... ..
NULL..