Directories and Links 369
18.13 Resolving a Pathname: realpath()................................................................................
The realpath() library function dereferences all symbolic links in pathname (a
null-terminated string) and resolves all references to /. and /.. to produce a null-
terminated string containing the corresponding absolute pathname.
The resulting string is placed in the buffer pointed to by resolved_path, which
should be a character array of at least PATH_MAX bytes. On success, realpath() also
returns a pointer to this resolved string.
The glibc implementation of realpath() allows the caller to specify resolved_path
as NULL. In this case, realpath() allocates a buffer of up to PATH_MAX bytes for the
resolved pathname and returns a pointer to that buffer as the function result. (The
caller must deallocate this buffer using free().) SUSv3 doesn’t specify this extension,
but it is specified in SUSv4.
The program in Listing 18-4 uses readlink() and realpath() to read the contents
of a symbolic link and to resolve the link to an absolute pathname. Here is an
example of the use of this program:
$ pwd Where are we?
/home/mtk
$ touch x Make a file
$ ln -s x y and a symbolic link to it
$ ./view_symlink y
readlink: y --> x
realpath: y --> /home/mtk/x
Listing 18-4: Read and resolve a symbolic link
––––––––––––––––––––––––––––––––––––––––––––––––––dirs_links/view_symlink.c
#include <sys/stat.h>
#include <limits.h> /* For definition of PATH_MAX */
#include "tlpi_hdr.h"
#define BUF_SIZE PATH_MAX
int
main(int argc, char *argv[])
{
struct stat statbuf;
char buf[BUF_SIZE];
ssize_t numBytes;
if (argc != 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s pathname\n", argv[0]);
#include <stdlib.h>
char *realpath(const char *pathname, char *resolved_path);
Returns pointer to resolved pathname on success, or NULL on error