STD:: FileSystem ::Perms您可以在文件上设置权限。 我想检查是否可以访问并写入文件。 如果我是文件的所有者,则使用此方法有效。 如果我不是文件的所有者(例如,扎根),那么返回的perms对于手头的任务而不知道所有者并不有用。
https://stackoverflow.com/a/7328340解释了如何在Linux系统上获得文件所有者和当前用户,该系统可以与STD:: filesystem ::Perms一起使用,以用于Linux上的Linux上的解决方案不符合POSIX。 有一种方法可以检查当前用户当前用户是否可以以POSIX的方式读取或写入文件?这只能仅使用C ++ STD LIB完成吗? Boost呢?
https://stackoverflow.com/a/10682224
建议无法使用Boost检测所有权。https://stackoverflow.com/a/59899055建议解释文件权限并不总是那么有意义,但是我只想知道我是否可以在尝试打开文件之前从文件中阅读。 triads:一个示例-RW-rw-r--
可以通过命令“ ID用户”在UNIX下获得使用权。例如:uid=1000(User) gid=1000(User) groups=1000(User),4(adm),7(lp),24(cdrom),27(sudo),30(dip)
使用者具有用户ID(UID),属于几个组。能够读取文件的能力基于UID和组数据。阅读可以通过一个过程完成,并且还具有UID/GUID参数 有很多文件,让我们谈谈有关常规文件而不是符号链接的最简单情况。我们需要检查树三合会
检查所选用户可以读取文件的内容很简单:
// Set here proper info about user
uid_t userId = getuid();
gid_t groupId = getgid();
std::string path = "myfile";
std::filesystem::path filePath(path);
auto status = std::filesystem::status(filePath);
struct stat fileStat;
stat(filePath.c_str(), &fileStat);
if (fileStat.st_uid == userId) {
// User is the same as the owner of the file
if ((status.permissions() & std::filesystem::perms::owner_read) !=
std::filesystem::perms::none) {
return true; // User could read file based on first triple
}
}
检查读取文件的权利更简单:
if ((status.permissions() & std::filesystem::perms::others_read) !=
std::filesystem::perms::none) {
return true; // User could read file based on third triple
}
组处理很复杂,因为我们必须检查所有用户属于:
// Get user name
struct passwd *pw = getpwuid(userId);
std::string username = pw->pw_name;
// Get groups list
std::vector<gid_t> groups;
int ngroups = 0;
uint result = getgrouplist(username.c_str(), groupId, nullptr, &ngroups);
groups.resize(ngroups);
result = getgrouplist(username.c_str(), groupId, groups.data(), &ngroups);
// Check all groups
for (uint i = 0; i < ngroups; ++i) {
if (groups[i] == fileStat.st_gid) {
// User belongs to a group that is equal to file group
if ((status.permissions() & std::filesystem::perms::group_read)!=
std::filesystem::perms::none) {
return true; // User could read file based on groups rights
}
}
}
该解决方案应在Linux和BSD系统上使用,但不是POSIX兼容
也没有ACL和RBAC文件权限,它们没有检查。这些权限不是标准的