[Previous]
[Contents]
[Next]

access()

check to see if a file or directory can be accessed

Synopsis:

#include <unistd.h>
int access( const char *path, int amode );

Description:

The access() function checks if the file or directory specified by path exists and if it can be accessed with the file access permissions given by amode. However, unlike other functions (open() for example), access() uses the real user ID and real group ID in place of the effective user and group IDs.

The value of amode is either the existence test, F_OK, or a bitwise ORing of the following access permissions to be checked, as defined in the header <unistd.h>:

R_OK
Test for read permission.
W_OK
Test for write permission.
X_OK
For a directory, test for search permission. Otherwise, test for execute permission.

Returns:

0
The file or directory exists and can be accessed with the specified mode.
-1
An error occurred. The errno variable indicates the reason for the error.

Errors:

EACCES
The permissions specified by amode are denied, or search permission is denied on a component of the path prefix.
EINVAL
An invalid value was specified for amode.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname component is longer than NAME_MAX.
ENOENT
A component of the path is not valid.
ENOTDIR
A component of the path prefix is not a directory.
EROFS
Write access was requested for a file residing on a read-only file system.

Examples:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main( int argc, char **argv )
  {
    if( argc!= 2 ) {
      fprintf( stderr, 
        "use: readable <filename>\n" );
      exit( 1 );
    }

    if( !access( argv[1], R_OK ) ) {
      printf( "ok to read %s\n", argv[1] );
      exit( 0 );
    } else {
      perror( argv[1] );
      exit( 1 );
    }
    return (EXIT_SUCCESS);
  }

Classification:

POSIX 1003.1

Safety:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

chmod(), errno, fstat(), open(), stat()


[Previous]
[Contents]
[Next]