fchmod() — Change the mode of a file or directory by descriptor
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1a |
both |
Format
#define _POSIX1_SOURCE 2
#include <sys/stat.h>
int fchmod(int fildes, mode_t mode);
General description
Sets the S_ISUID, S_ISGID, and file permission bits of the open file identified by fildes, its file descriptor.
The mode argument is created with one of the symbols defined in the sys/stat.h header file. For more information on these symbols, refer to chmod() — Change the mode of a file or directory.
Returned value
If successful, fchmod() marks for update the st_ctime field of the file and returns 0.
If unsuccessful, fchmod() returns -1 and sets errno
to one of the following values:
- Error Code
- Description
- EBADF
- fildes is not a valid open file descriptor.
- EPERM
- The effective user ID (UID) does not match the owner of the file, and the calling process does not have appropriate privileges.
- EROFS
- The file resides on a read-only file system.
Example
CELEBF03
/* CELEBF03
This example changes a file permission.
*/
#define _POSIX_SOURCE
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
char fn[]="temp.file";
int fd;
struct stat info;
if ((fd = creat(fn, S_IWUSR)) < 0)
perror("creat() error");
else {
stat(fn, &info);
printf("original permissions were: %08x\n", info.st_mode);
if (fchmod(fd, S_IRWXU|S_IRWXG) != 0)
perror("fchmod() error");
else {
stat(fn, &info);
printf("after fchmod(), permissions are: %08x\n", info.st_mode);
}
close(fd);
unlink(fn);
}
}
Output
original permissions were: 03000080
after fchmod(), permissions are: 030001f8