gpt4 book ai didi

c - C中的文件创建权限

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:54 26 4
gpt4 key购买 nike

我正在使用以下代码在 C 中创建一个文件:

int outfd = open(arg,O_CREAT|O_TRUNC|O_WRONLY, f_per);

f_per 是文件权限编号。

f_per 设置为 0644,执行代码并执行 ls -l 给我设置为 -rw-r-- 的(输出)文件权限r-- 这是预期的。但是,将内容设置为 0777 会授予 -rwxrwxr-x 而不是 -rwxrwxrwx 的权限。知道为什么会这样吗?

最佳答案

根据 POSIX page for the open call ,在 O_CREAT 下:

... the access permission bits of the file mode shall be set to the value of the argument following the oflag argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask.

模式创建掩码(或 umask)可以被认为是一个减法掩码。例如,如果您在文件模式创建掩码为 --------w-/0002 时尝试创建具有权限 rwxrwxrwx/0777 的文件,则您实际上最终会是:

  rwxrwxrwx
& rwxrwxr-x (complement of -------w-)
=========
rwxrwxr-x

这似乎是您遇到的情况。

如果你想实际创建一个特定权限的文件,你可以通过将它设置为零(然后恢复它)来暂时禁用 umask,就像:

mode_t oldmask = umask(0); // needs sys/stat.h
int outfd = open(arg, O_CREAT|O_TRUNC|O_WRONLY, 0777);
umask(oldmask);

关于c - C中的文件创建权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com