我想在 Unix 中创建一个允许所有人访问的文件。 如果该文件已经存在,则应将其截断为空。
阅读打开的手册页后,我有以下调用。只是想确认这样做是否正确。
int fd;
int flags = O_RDWR | O_CREAT | O_TRUNC;
/* Set umask to Octal 011 */
mode_t mode = S_IXGRP | S_IXOTH;
/* umask syscall alwasy succeeds. No need to save return value (previous umask value) */
umask(mode);
/* Set mode to Octal 666. open syscall will and mode with ~umask.
0666 & ~0011 = 0666 i.e. the mode we want to set.
*/
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
if ((fd = open(path.c_str(), flags, mode)) < 0) {
return false;
} else {
close(fd);
return true;
}
谢谢!
编辑:根据 Nikolai 的评论,所有访问权限 = 读取和写入。我不希望每个人都能够写入可执行文件。
最佳答案
您可以保证文件创建模式的唯一方法是在调用 open
之前明确地将您的 umask 清零,因为 mode
参数是针对您的 umask 的 NAND。
您创建
它之后,最好简单地设置您的文件模式。
关于c++ - open() 的参数 : Everyone should have all access to file & should be truncated on creation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12322818/