c - C中的文件创建权限

标签 c file file-permissions

我正在使用以下代码在 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/

相关文章:

linux - 权限问题,无法以 root 身份运行脚本

android - 如何保存回 Assets 文件夹中的文件

Java SE 6 和 Java SE 8 JRE 在 Windows 7 上的行为不同(文件权限)

c - linux引导代码怎么用C写的?

c - 数字字符串上的 STRCMP

c - 在c中验证BST的最佳方法

C - 动态修改文件 - 这可能吗?

c - 使用 C 中的文本文件的银行帐户存款选项

java - 使用 Stream 加载和处理文件

git - 如何读取 git-ls-tree 输出的模式字段