命名空间
变体
操作

std::filesystem::perms

来自 cppreference.cn
 
 
 
定义于头文件 <filesystem>
enum class perms;
(自 C++17 起)

此类型表示文件访问权限。

perms 满足 位掩码类型 的要求(这意味着为此类型定义了位运算符 operator&operator|operator^operator~operator&=operator|=operator^=)。 none 表示空位掩码;每个其他枚举器都表示不同的位掩码元素。

访问权限模型 POSIX 权限位,以及任何单独的文件权限(如 filesystem::status 报告的)是一些以下位的组合

目录

[编辑] 成员常量

成员常量 值(八进制) POSIX 等价物 含义
none 0 未设置任何权限位
owner_read 0400 S_IRUSR 文件所有者拥有读取权限
owner_write 0200 S_IWUSR 文件所有者拥有写入权限
owner_exec 0100 S_IXUSR 文件所有者拥有执行/搜索权限
owner_all 0700 S_IRWXU 文件所有者拥有读取、写入和执行/搜索权限

等价于 owner_read | owner_write | owner_exec

group_read 040 S_IRGRP 文件用户组拥有读取权限
group_write 020 S_IWGRP 文件用户组拥有写入权限
group_exec 010 S_IXGRP 文件用户组拥有执行/搜索权限
group_all 070 S_IRWXG 文件用户组拥有读取、写入和执行/搜索权限

等价于 group_read | group_write | group_exec

others_read 04 S_IROTH 其他用户拥有读取权限
others_write 02 S_IWOTH 其他用户拥有写入权限
others_exec 01 S_IXOTH 其他用户拥有执行/搜索权限
others_all 07 S_IRWXO 其他用户拥有读取、写入和执行/搜索权限

等价于 others_read | others_write | others_exec

all 0777 所有用户拥有读取、写入和执行/搜索权限

等价于 owner_all | group_all | others_all

set_uid 04000 S_ISUID 执行时设置用户 ID 为文件所有者用户 ID
set_gid 02000 S_ISGID 执行时设置组 ID 为文件用户组 ID
sticky_bit 01000 S_ISVTX 实现定义的含义,但 POSIX XSI 指定当在目录上设置时,即使目录对其他人可写,也只有文件所有者可以删除文件(与 /tmp 一起使用)
mask 07777 所有有效的权限位。

等价于 all | set_uid | set_gid | sticky_bit

此外,还定义了此类型的以下常量,它们不表示权限

成员常量 值(十六进制) 含义
unknown 0xFFFF 未知权限(例如,当 filesystem::file_status 在没有权限的情况下创建时)

[编辑] 注解

权限可能不一定以位实现,但概念上是这样处理的。

某些权限位可能在某些系统上被忽略,并且更改某些位可能会自动更改其他位(例如,在没有所有者/组/所有区别的平台上,设置三个写入位中的任何一个都会设置所有三个)。

[编辑] 示例

#include <filesystem>
#include <fstream>
#include <iostream>
 
void demo_perms(std::filesystem::perms p)
{
    using std::filesystem::perms;
    auto show = [=](char op, perms perm)
    {
        std::cout << (perms::none == (perm & p) ? '-' : op);
    };
    show('r', perms::owner_read);
    show('w', perms::owner_write);
    show('x', perms::owner_exec);
    show('r', perms::group_read);
    show('w', perms::group_write);
    show('x', perms::group_exec);
    show('r', perms::others_read);
    show('w', perms::others_write);
    show('x', perms::others_exec);
    std::cout << '\n';
}
 
int main()
{
    std::ofstream("test.txt"); // create file
 
    std::cout << "Created file with permissions: ";
    demo_perms(std::filesystem::status("test.txt").permissions());
 
    std::filesystem::permissions(
        "test.txt",
        std::filesystem::perms::owner_all | std::filesystem::perms::group_all,
        std::filesystem::perm_options::add
    );
 
    std::cout << "After adding u+rwx and g+rwx:  ";
    demo_perms(std::filesystem::status("test.txt").permissions());
 
    std::filesystem::remove("test.txt");
}

可能的输出

Created file with permissions: rw-r--r--
After adding u+rwx and g+wrx:  rwxrwxr--

[编辑] 参见

(C++17)(C++17)
确定文件属性
确定文件属性,检查符号链接目标
(函数) [编辑]
修改文件访问权限
(函数) [编辑]