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

Dul*_*ula 12 c++ linux file-ownership

如何使用C++获取Linux文件系统上文件的所有者名称和组名?该stat()呼叫仅提供所有者ID和组ID,但不提供实际名称.

-rw-r--r--.  1 john devl  3052 Sep  6 18:10 blah.txt
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*ler 24

使用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
Run Code Online (Sandbox Code Playgroud)

  • 为了完整性,请注意*"getpwnam()和getpwuid()分别在密码数据库中搜索给定的登录名或用户uid,**总是返回遇到的第一个**"*(强调添加)因为一个UID可以关联有多个用户名(认为这通常不赞成). (3认同)