![[C++] fchmod 代码修改文件权限,第1张 [C++] fchmod 代码修改文件权限,第1张](/aiimages/%5BC%2B%2B%5D+fchmod+%E4%BB%A3%E7%A0%81%E4%BF%AE%E6%94%B9%E6%96%87%E4%BB%B6%E6%9D%83%E9%99%90.png)
一、需求:
通过代码实现 文件权限的修改(前提文件必须有读的权限)
二、实现:
#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;
}
三、执行结果:
- 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
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)