c - 如何匹配open和stat mode_t?

标签 c unix posix file-permissions

我正在使用 open 创建文件并设置其权限,然后我使用 stat 获取文件权限....权限不匹配。 下面程序的结果是:

mode from open (600) and stat (100600) are different



如何比较 open(2) 设置的模式(权限)与 stat(2) 检索的模式(权限)?

#include <sys/types.h>
#include <sys/stat.h>

#include <fcntl.h>
#include <stdio.h>


int
main(int argc, char **argv, char **env) {
        
        const char *path = "/tmp/test";
        const mode_t mode = S_IRUSR | S_IWUSR;
        
        if (open(path, O_RDWR |  O_CREAT | O_EXCL, mode) == -1)
                err(1, "open for '%s' failed", path);
        
        struct stat sb;
        if (stat(path, &sb) != 0)
                err(2, "stat failed");
        
        if (mode != sb.st_mode)
                printf("mode from open (%o) and stat (%o) are different\n", 
                        mode, sb.st_mode);

        return 0;
}

谢谢

最佳答案

这是因为 st_mode 成员不仅包含访问权限,还包含许多其他标志(例如,您可以检查文件是否是符号链接(symbolic link))。 Docs here .

关于c - 如何匹配open和stat mode_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24314397/

相关文章:

c - C 中的文件描述符

c - 使用带有 tolower() 或 toupper() 的 putchar() 打印 A-Z 在第一个字符处停止循环

c - Realloc 在第二个循环中停止程序

c++ - 使用文件指针通过 TCP 传输文件的问题

c - 在Unix/Linux shell编程:the difference between > and >&

c - 在实际打开文件之前验证文件路径

c - 使用多线程时保护全局变量

c - 通过 fscanf() 读取的值未打印出来

c - LED 闪烁顺序

linux - 联机帮助页中 Unix 命令名称后括号中的数字是什么意思?