link()

Create a link to an existing file

Synopsis:

#include <unistd.h>

int link( const char* existing, 
          const char* new );

Arguments:

existing
The path of an existing file.
new
The path for the new link.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The link() function creates a new directory entry named by new to refer to (that is, to be a link to) an existing file named by existing. The function atomically creates a new link for the existing file, and increments the link count of the file by one.


Note: This implementation doesn't support using link() on directories or the linking of files across filesystems (different logical disks).

If the function fails, no link is created, and the link count of the file remains unchanged.

If link() succeeds, the st_ctime field of the file and the st_ctime and st_mtime fields of the directory that contains the new entry are marked for update.

Returns:

0
Success.
-1
An error occurred (errno is set).

Errors:

EACCES
A component of either path prefix denies search permission, or the link named by new is in a directory with a mode that denies write permission.
EEXIST
The link named by new already exists.
ELOOP
Too many levels of symbolic links or prefixes.
EMLINK
The number of links to the file named by existing would exceed LINK_MAX.
ENAMETOOLONG
The length of the existing or new string exceeds PATH_MAX, or a pathname component is longer than NAME_MAX.
ENOENT
This error code can mean the following:
ENOSPC
The directory that would contain the link can't be extended.
ENOSYS
The link() function isn't implemented for the filesystem specified in existing or new.
ENOTDIR
A component of either path prefix isn't a directory.
EPERM
The file named by existing is a directory.
EROFS
The requested link requires writing in a directory on a read-only file system.
EXDEV
The link named by new and the file named by existing are on different logical disks.

Examples:

/*
 * The following program performs a rename
 * operation of argv[1] to argv[2].
 * Please note that this example,  unlike the
 * library function rename(), ONLY works if
 * argv[2] doesn't already exist.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main( int argc, char** argv )
  {
    /* Create a link of argv[1] to argv[2].
     */
    if( link( argv[1], argv[2] ) == -1 ) {
      perror( "link" );
      return( EXIT_FAILURE );
    }
    if( unlink( argv[1] ) == -1 ) {
      perror( argv[1] );
      return( EXIT_FAILURE );
    }
    return( EXIT_SUCCESS );
  }

Classification:

POSIX 1003.1

Safety:
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

See also:

errno, rename(), symlink(), unlink()