[C++] fchmod 代码修改文件权限

[C++] fchmod 代码修改文件权限,第1张

一、需求:
通过代码实现 文件权限的修改(前提文件必须有读的权限)

二、实现:

#include
#include 
#include
#include
#include
#include
#include 
#include 
#include 

void UpdatechmodAvatar(const std::string& avatar) {
    FILE *fp;
    if (NULL == (fp = fopen(avatar.c_str(), "rb"))) {
        printf("fopen avatar %s file failed! errno%d (%s)\n", avatar.c_str(), errno, strerror(errno));
    }
    else {
        mode_t  old_mode = umask(0);
        printf("avatar %s\n", avatar.c_str());
        int fd = fileno(fp);
        if (fchmod(fd, S_IRWXU|S_IRWXG|S_IRWXO)) {
            printf("fchmod failed! errno%d (%s)\n", errno, strerror(errno));
        }
        umask(old_mode);
        fclose(fp);
    }
}

int main()
{
	printf("hello\n");
	UpdatechmodAvatar("test");
	printf("end\n");
	return 0;
}

三、执行结果:

  1. 000test

hunt@hunt:~/hunt/project1$ chmod 000 test
hunt@hunt:~/hunt/project1$ ./main
hello
fopen avatar test file failed! errno13 (Permission denied)
end

2.400test

hunt@hunt:~/hunt/project1$ chmod 400 test
hunt@hunt:~/hunt/project1$ ./main
hello
avatar test
end
hunt@hunt:~/hunt/project1$ ls -l test
-rwxrwxrwx 1 ts ts 0 5月 11 15:09 test

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/915306.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存