当前位置: 代码迷 >> 综合 >> chmod、fchmod和fchmodat函数
  详细解决方案

chmod、fchmod和fchmodat函数

热度:73   发布时间:2024-03-10 00:28:24.0

chmod、fchmod和fchmodat,可更改现有文件的访问权限。

#include<sys/stat.h>
int chmod(const char *pathname, mode_t mode);
int fchmod(const char *pathname, mode_t mode);
int fchmodat(int fd, const char *pathname, mode_t mode, int flag);

chmod在指定的文件上进行操作。
fchmod对已打开的文件进行操作。
fchmodat与chmod在两种情况下是相同的:一种是pathname为绝对路径,另一种是fd参数为AT_FDCWD而pathname为相对路径。否则,fchmodat计算相对于打开目录(fd指向,即fd打开的文件所在的目录)的pathname。

flag参数用于改变fchmod的行为,当设置了AT_SYMLINK_NOFOLLOW标志时,fchmodat并不会跟随符号链接。

mode参数的常量:

mode 说明
S_ISUID 执行时设置用户ID
S_ISGID 执行时设置组ID
S_ISVTX 保存正文
S_IRWXU 用户(所有者)读、写和执行
S_IRUSR 用户(所有者)读
S_IWUSR 用户(所有者)写
S_IXUSR 用户(所有者)执行
S_IRWXG 组读、写和执行
S_IRGRP 组读
S_IWGRP 组写
S_IXGRP 组执行
S_IRWXO 其他读、写和执行
S_IROTH 其他读
S_IWOTH 其他写
S_IXOTH 其他执行

返回值:
成功,返回0
出错,返回-1

#include<sys/stat.h>
#include<stdio.h>
int main()
{
    int r = chmod("test.txt",S_IRWXU);if(r==0){
    printf("mod changed successfully!\n");}return 0;
}