如何使用C++在 Linux 中获取文件的所有者名称?

How to get file's owner name in Linux using C++?

本文关键字:所有者 文件 获取 C++ 何使用 Linux      更新时间:2023-10-16

如何使用c++获取Linux文件系统上文件的所有者名称和组名称?stat()调用只给我所有者ID和组ID,而不是实际的名称。

-rw-r--r--.  1 john devl  3052 Sep  6 18:10 blah.txt

如何以编程方式获得'john'和'devl' ?

使用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

一种方法是使用stat()获取文件的uid,然后使用getpwuid()获取用户名作为字符串。