[Previous]
[Contents]
[Next]

chmod()

change the permissions for a file

Synopsis:

#include <sys/types.h>
#include <sys/stat.h>
int chmod( const char *path, mode_t mode );

Description:

The chmod() function changes the permissions for a file specified by path to be the settings in the mode given by mode.

If the effective user ID of the calling process is equal to the file owner, or the calling process has appropriate privileges (for example, it belongs to the super user), chmod() sets the S_ISUID, S_ISGID and the file permission bits, defined in the <sys/stat.h> header file, from the corresponding bits in the mode argument. These bits define access permissions for the user associated with the file, the group associated with the file and all others.

If the calling process does not have appropriate privileges, and if the group ID of the file does not match the effective group ID, and the file is a regular file, bit S_ISGID (set group ID on execution) in the file's mode is cleared upon successful return from chmod().

This call has no effect on file descriptors for files that are already open.

If chmod() succeeds, the st_ctime field of the file is marked for update.

Returns:

0
Success
-1
An error occurred - errno is set to indicate the error.

Errors:

EACCES
Search permission is denied on a component of the path prefix.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname component is longer than NAME_MAX.
ENOTDIR
A component of the path prefix is not a directory.
ENOENT
The named file does not exist, or the path arguments points to an empty string.
EPERM
The effective user ID does not match the owner of the file, and the calling process does not have appropriate privileges.
EROFS
The named file resides on a read-only file system.

Examples:

/*
 * change the permissions of a list of files
 * to by read/write by the owner only
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

int main( int argc, char **argv )
  {
    int i;
    int ecode = 0;

    for( i = 1; i < argc; i++ ) {
      if( chmod( argv[i], S_IRUSR | S_IWUSR ) == -1 ) {
        perror( argv[i] );
        ecode++;
      }
    }
    return( ecode );
  }

Classification:

POSIX 1003.1

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

See also:

chown(), errno, fchmod(), fchown(), fstat(), open(), stat()


[Previous]
[Contents]
[Next]