【发布时间】:2011-09-07 02:39:14
【问题描述】:
如何使用 C++ 获取 Linux 文件系统上文件的所有者名称和组名称? stat() 调用只给了我所有者 ID 和组 ID,而不是实际名称。
-rw-r--r--. 1 john devl 3052 Sep 6 18:10 blah.txt
如何以编程方式获取“john”和“devl”?
【问题讨论】:
标签: c++ linux file-ownership
如何使用 C++ 获取 Linux 文件系统上文件的所有者名称和组名称? stat() 调用只给了我所有者 ID 和组 ID,而不是实际名称。
-rw-r--r--. 1 john devl 3052 Sep 6 18:10 blah.txt
如何以编程方式获取“john”和“devl”?
【问题讨论】:
标签: c++ linux file-ownership
使用getpwuid() 和getgrgid()。
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
struct stat info;
stat(filename, &info); // Error check omitted
struct passwd *pw = getpwuid(info.st_uid);
struct group *gr = getgrgid(info.st_gid);
// If pw != 0, pw->pw_name contains the user name
// If gr != 0, gr->gr_name contains the group name
【讨论】:
getgrent() 来查找用户jdoe 是否实际上是组1234 的成员。
一种方法是使用stat() 获取文件的uid,然后使用getpwuid() 以字符串形式获取用户名。
【讨论】: