Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1 |
both |
#define _POSIX_SOURCE
#include <unistd.h>
int chown(const char *pathname, uid_t owner, gid_t group);
Changes the owner or group (or both) of a file. pathname is the name of the file whose owner or group you want to change. owner is the user ID (UID) of the new owner of the file. group is the group ID (GID) of the new group for the file.
If _POSIX_CHOWN_RESTRICTED is defined in the unistd.h header file, a process can change the group of a file only if one of these is true:
If pathname is a regular file and one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, chown() clears the set-user-ID (S_ISUID) and set-group-ID (S_ISGID) bits of the file mode and returns successfully.
If pathname is not a regular file and one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, chown() clears the set-user-ID (S_ISUID) and set-group-ID (S_ISGID) bits of the file.
When chown() completes successfully, it marks the st_ctime field of the file to be updated.
Special behavior for XPG4.2: If owner or group is specified as (uid_t)-1 or (gid_t)-1 respectively, the corresponding ID of the file is unchanged.
If successful, chown() updates the owner, group, and change time for the file and returns 0.
⁄* CELEBC12
This example changes the owner and group of a file.
*⁄
#define _POSIX_SOURCE
#include <unistd.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#undef _POSIX_SOURCE
#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);
}
}
original owner was 0 and group was 0
after chown(), owner is 25 and group is 0