一、需求:
通过代码实现 文件权限的修改(前提文件必须有读的权限)
二、实现:
#include<iostream>
#include <stdio.h>
#include<stddef.h>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
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