Namespaces
Variants

std::filesystem:: permissions

From cppreference.net
定义于头文件 <filesystem>
void permissions ( const std:: filesystem :: path & p,

std:: filesystem :: perms prms,

std:: filesystem :: perm_options opts = perm_options :: replace ) ;
(1) (C++17 起)
void permissions ( const std:: filesystem :: path & p,

std:: filesystem :: perms prms,

std:: error_code & ec ) noexcept ;
(2) (C++17 起)
(3) (C++17 起)

修改 p 所解析文件的访问权限,操作方式类似于 POSIX fchmodat 。除非在 opts 中设置了 perm_options::nofollow ,否则会遵循符号链接。

第二个签名的行为如同调用时将 opts 设置为 perm_options :: replace

效果取决于 prms opts ,具体如下:

  • opts perm_options :: replace ,文件权限将被精确设置为 prms & std:: filesystem :: perms :: mask (即 prms 中的每个有效位都会被应用)。
  • opts perm_options :: add ,文件权限将被精确设置为 status ( p ) . permissions ( ) | ( prms & perms :: mask ) (即对于 prms 中已设置但文件当前权限中未设置的有效位,会将其添加到文件权限中)。
  • opts perm_options :: remove ,文件权限将被精确设置为 status ( p ) . permissions ( ) & ~ ( prms & perms :: mask ) (即对于 prms 中未设置但文件当前权限中已设置的有效位,会将其从文件权限中清除)。

opts 必须仅设置 replace add remove 中的一项。

非抛出重载在出错时没有特殊操作。

目录

参数

p - 要检查的路径
prms - 要设置、添加或删除的权限
opts - 控制此函数执行操作的选项
ec - 非抛出重载中用于错误报告的输出参数

返回值

(无)

异常

任何未标记为 noexcept 的重载在内存分配失败时可能抛出 std::bad_alloc

1) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,该异常以 p 作为第一个路径参数,以操作系统错误代码作为错误码参数构造。
2,3) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统API错误码;若无错误发生,则执行 ec. clear ( )

注释

权限不一定以位的形式实现,但在概念上被视作位处理。

某些权限位在某些系统上可能被忽略,且修改某些位可能自动改变其他位(例如在没有所有者/组/全体区分的平台上,设置三个写入位中的任意一个会同时设置所有三个)。

示例

#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"); // 创建文件
    std::cout << "创建文件时的权限: ";
    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 << "添加 u+rwx 和 g+rwx 后:  ";
    demo_perms(std::filesystem::status("test.txt").permissions());
    std::filesystem::remove("test.txt");
}

可能的输出:

创建文件时的权限: rw-r--r--
添加 u+rwx 和 g+wrx 后:  rwxrwxr--

参见

(C++17)
标识文件系统权限
(枚举)
(C++17) (C++17)
确定文件属性
确定文件属性,检查符号链接目标
(函数)