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

后端 未结 2 1005
慢半拍i
慢半拍i 2020-12-29 10:44

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 actua

相关标签:
2条回答
  • 2020-12-29 11:08

    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
    
    0 讨论(0)
  • 2020-12-29 11:14

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

    0 讨论(0)
提交回复
热议问题