栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

二、实现:

#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 %sn", 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("hellon");
	UpdatechmodAvatar("test");
	printf("endn");
	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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876542.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号