gtpc2m5pC/C++ Language Support User's Guide

readlink-Read the Value of a Symbolic Link

This function reads the value of a symbolic link.

Format

#include <unistd.h>
int readlink(const char *path, char *buf, size_t bufsiz);

path
The name of a symbolic link.

buf
The address of the array of characters where the symbolic link is to be read.

bufsiz
The number of the character to read.

This function places the contents of symbolic link path in buffer buf. The size of the buffer is indicated by bufsiz. The result stored in buf does not include a terminating null character.

If the buffer is too small to contain the value of the symbolic link, that value is truncated to the size of the buffer (bufsiz). If the value returned is the size of the buffer, use the lstat function to determine the actual size of the symbolic link.

Normal Return

When bufsiz is greater than 0 and the readlink function has completed successfully, the readlink function returns the number of bytes placed in the buffer. When bufsiz is 0 and the readlink function has otherwise completed successfully, the readlink function returns the number of bytes contained in the symbolic link and the buffer is not changed.

If the returned value is equal to bufsiz, you can determine the contents of the symbolic link by using either the lstat function or the readlink function with a 0 value for bufsiz.

Error Return

If the readlink function is not successful, it returns a value of -1 and sets errno to one of the following:

ENOTDIR
A component of the path prefix is not a directory.

ENAMETOOLONG
path is longer than PATH_MAX characters or some component of pathname is longer than NAME_MAX characters. For symbolic links, the length of the path name string substituted for a symbolic link exceeds PATH_MAX.

ENOENT
The named file does not exist.

EACCES
Search permission is denied for a component of the path prefix.

ELOOP
A loop exists in symbolic links. This error is issued if the number of symbolic links found while resolving the path argument. is greater than POSIX_SYMLOOP.

EINVAL
The named file is not a symbolic link.

Programming Considerations

None.

Examples

The following example provides readlink information for a file.

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
 
main() {
  char fn[]="readlink.file";
  char sl[]="readlink.symlink";
  char buf[30];
  int  fd;
 
  if ((fd = creat(fn, S_IWUSR)) < 0)
    perror("creat() error");
  else {
    close(fd);
    if (symlink(fn, sl) != 0)
      perror("symlink() error");
    else {
      if (readlink(sl, buf, sizeof(buf)) < 0)
        perror("readlink() error");
      else printf("readlink() returned '%s' for '%s'\n", buf, sl);
 
      unlink(sl);
    }
    unlink(fn);
  }
}

Output

readlink() returned 'readlink.file' for 'readlink.symlink'

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.