简体   繁体   English

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

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

How can I get get the owner name and group name of a file on a Linux filesystem using C++? 如何使用C ++获取Linux文件系统上文件的所有者名称和组名? The stat() call only gives me owner ID and group ID but not the actual name. stat()调用仅提供所有者ID和组ID,但不提供实际名称。

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

How can I get 'john' and 'devl' programmatically? 我如何以编程方式获得“john”和“devl”?

Use getpwuid() and getgrgid() . 使用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()将用户名作为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM