The Linux Programming Interface

(nextflipdebug5) #1

370 Chapter 18


if (lstat(argv[1], &statbuf) == -1)
errExit("lstat");

if (!S_ISLNK(statbuf.st_mode))
fatal("%s is not a symbolic link", argv[1]);

numBytes = readlink(argv[1], buf, BUF_SIZE - 1);
if (numBytes == -1)
errExit("readlink");
buf[numBytes] = '\0'; /* Add terminating null byte */
printf("readlink: %s --> %s\n", argv[1], buf);

if (realpath(argv[1], buf) == NULL)
errExit("realpath");
printf("realpath: %s --> %s\n", argv[1], buf);

exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––dirs_links/view_symlink.c

18.14 Parsing Pathname Strings: dirname() and basename()


The dirname() and basename() functions break a pathname string into directory and
filename parts. (These functions perform a similar task to the dirname(1) and
basename(1) commands.)

For example, given the pathname /home/britta/prog.c, dirname() returns /home/britta
and basename() returns prog.c. Concatenating the string returned by dirname(), a
slash (/), and the string returned by basename() yields a complete pathname.
Note the following points regarding the operation of dirname() and basename():

z Trailing slash characters in pathname are ignored.
z If pathname doesn’t contain a slash, then dirname() returns the string. (dot)
and basename() returns pathname.
z If pathname consists of just a slash, then both dirname() and basename() return
the string /. Applying the concatenation rule above to create a pathname from
these returned strings would yield the string ///. This is a valid pathname.
Because multiple consecutive slashes are equivalent to a single slash, the path-
name /// is equivalent to the pathname /.

#include <libgen.h>

char *dirname(char *pathname);
char *basename(char *pathname);
Both return a pointer to a null-terminated (and possibly
statically allocated) string
Free download pdf