一、需求:
通过代码实现 文件权限的修改(前提文件必须有读的权限)
二、实现:
#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; }
三、执行结果:
- 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


![[C++] fchmod 代码修改文件权限 [C++] fchmod 代码修改文件权限](http://www.mshxw.com/aiimages/31/876542.png)
