15

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?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Dula
  • 1,404
  • 1
  • 14
  • 29

2 Answers2

29

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
swdev
  • 2,941
  • 2
  • 25
  • 37
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    For completeness note that *"getpwnam() and getpwuid() search the password database for the given login name or user uid, respectively, **always returning the first one encountered**"* (emphasis added) because one UID can be associated with more than one username (thought this is generally frowned upon). – dmckee --- ex-moderator kitten Sep 07 '11 at 03:39
  • Fair comment. One of the banes of my life is that the local group file has multiple entries for GID 1234 with different names. It tends to mean `getgrent()` to find whether user `jdoe` is actually a member of group 1234. – Jonathan Leffler Sep 07 '11 at 03:46
4

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

jedwards
  • 29,432
  • 3
  • 65
  • 92