std::filesystem::permissions
来自cppreference.com
< cpp | filesystem
<tbody>
</tbody>
| 在标头 <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 起) |
void permissions( const std::filesystem::path& p, std::filesystem::perms prms, std::filesystem::perm_options opts, std::error_code& ec ); |
(3) | (C++17 起) |
更改 p 所解析的文件的访问权限,如同用 POSIX fchmodat。跟随符号链接,除非在 opts 中设置了 perm_options::nofollow。
第二个签名表现如同以设为 perm_options::replace 的 opts 调用。
效果按如下方式依赖于 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) 抛出 std::filesystem::filesystem_error,构造时以
p 为第一路径实参并以OS 错误码为错误码实参。注解
权限不必用位实现,但概念上用这种方式处理它们。
某些系统上某些权限位可能被忽略,而更改某些位可能自动影响其他位(例如在无所有者/组/全体区分的平台上,设置三者任一部分都会写入三者全体)。
示例
运行此代码
#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+rwx 后: rwxrwxr--
参阅
(C++17) |
标识文件系统权限 (枚举) |
(C++17)(C++17) |
确定文件属性 确定文件属性,检查符号链接目标 (函数) |