gtpc2m0qC/C++ Language Support User's Guide

chown-Change the Owner or Group of a File or Directory

This function changes the owner or group of a file or directory.

Format

#include <unistd.h>
int chown(const char *pathname, uid_t owner, gid_t group)

pathname
The name of the file whose owner and group are to be changed.

owner
The user ID (UID) of the new owner of the file.

group
The group ID (GID) of the new group for the file.

A process can change the ownership of a file if the effective user ID of the process is equal to the user ID of the file owner or if the process has appropriate privileges (superuser authority). If the file is a regular file and the process does not have superuser authority, the chown function clears the S_ISUID and S_ISGID bits in the mode of the file.

TPF deviation from POSIX

The TPF system does not support the ctime time stamp.

Normal Return

If successful, chown updates the owner and group for the file and returns 0.

Error Return

If unsuccessful, chown returns -1 and sets errno to one of the following:

EACCES
The process does not have search permission on some component of the pathname prefix.

EINVAL
owner or group is not a valid user ID (UID) or group ID (GID).

ELOOP
A loop exists in symbolic links. This error is issued if the number of symbolic links detected in the resolution of pathname is greater than POSIX_SYMLOOP (a value defined in the limits.h header file).

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

ENOENT
There is no file named pathname or the pathname parameter is an empty string.

ENOTDIR
Some component of the pathname prefix is not a directory.

EPERM
The user ID of the calling process does not match the owner of the file.

Programming Considerations

None.

Examples

The following example changes the owner and group of a file.

#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
 
main() {
  char fn[]="temp.file";
  FILE *stream;
  struct stat info;
 
  if ((stream = fopen(fn, "w")) == NULL)
    perror("fopen() error");
  else {
    fclose(stream);
    stat(fn, &info);
    printf("original owner was %d and group was %d\n", info.st_uid,
           info.st_gid);
    if (chown(fn, 25, 0) != 0)
      perror("chown() error");
    else {
      stat(fn, &info);
      printf("after chown(), owner is %d and group is %d\n",
             info.st_uid, info.st_gid);
    }
    unlink(fn);
  }
}

Output

original owner was 0 and group was 0
after chown(), owner is 25 and group is 0

Related Information

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