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

故事扮演 提交于 2020-01-20 18:58:08

问题


How can I get get the owner name and group name of a file on a Linux filesystem using C++? The stat() call only gives me owner ID and group ID but not the actual name.

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

How can I get 'john' and 'devl' programmatically?


回答1:


Use getpwuid() and 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



回答2:


One way would be to use stat() to get the uid of a file and then getpwuid() to get the username as a string.



来源:https://stackoverflow.com/questions/7328327/how-to-get-files-owner-name-in-linux-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!