std::filesystem::permissions

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

                 std::filesystem::perms prms,
                 std::filesystem::perm_options opts = perm_options::replace);
void permissions(const std::filesystem::path& p,
                 std::filesystem::perms prms,
                 std::error_code& ec) noexcept;
void permissions(const std::filesystem::path& p,
                 std::filesystem::perms prms,
                 std::filesystem::perm_options opts,

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

更改 p 所决定的文件的访问权限,如同用 POSIX fchmodat 。跟随符号链接,除非在 opts 中设置了 perm_options::nofollow

第二个签名表现如同以设为 perm_options::replaceopts 调用

效果按如下方式依赖于 prmsopts

opts 要求 replaceaddremove 中有且仅有一者被设置。

不抛出重载在错误时无特殊行动。

目录

参数

p - 要检验的路劲
prms - 要设置、添加或移除的权限
opts - 控制此函数所采用行动的选项
ec - 不抛出重载中报告错误的输出参数

返回值

(无)

异常

不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一参数 p 和作为错误码参数的 OS 错误码构造。若内存分配失败则可能抛出 std::bad_alloc 。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear()

注意

权限不必用位实现,但概念上用该方式处理它们。

某些系统上某些权限位可能被忽略,而更改某些位可能自动影响其他(例如在无拥有者/群/全体区别的平台上,设置三者任一部分都会写入三者全体的位集)

示例

#include <fstream>
#include <bitset>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
void demo_perms(fs::perms p)
{
    std::cout << ((p & fs::perms::owner_read) != fs::perms::none ? "r" : "-")
              << ((p & fs::perms::owner_write) != fs::perms::none ? "w" : "-")
              << ((p & fs::perms::owner_exec) != fs::perms::none ? "x" : "-")
              << ((p & fs::perms::group_read) != fs::perms::none ? "r" : "-")
              << ((p & fs::perms::group_write) != fs::perms::none ? "w" : "-")
              << ((p & fs::perms::group_exec) != fs::perms::none ? "x" : "-")
              << ((p & fs::perms::others_read) != fs::perms::none ? "r" : "-")
              << ((p & fs::perms::others_write) != fs::perms::none ? "w" : "-")
              << ((p & fs::perms::others_exec) != fs::perms::none ? "x" : "-")
              << '\n';
}
int main()
{
    std::ofstream("test.txt"); // 创建文件
 
    std::cout << "Created file with permissions: ";
    demo_perms(fs::status("test.txt").permissions());
 
    fs::permissions("test.txt",
                    fs::perms::owner_all | fs::perms::group_all,
                    fs::perm_options::add);
 
    std::cout << "After adding o+rwx and g+rwx:  ";
    demo_perms(fs::status("test.txt").permissions());
 
    fs::remove("test.txt");
}

可能的输出:

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

参阅

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

版本历史

  • (当前 | 先前) 2017年4月30日 (日) 11:06Fruderica讨论 | 贡献. . (2,658字节) (+2,658). . (以“{{cpp/filesystem/title|permissions}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | since=c++17 |1= void permissions(const std::filesyst...”为内容创建页面)