I am trying to get a C string of the owner and group of a file, After I do a stat()
I get the user ID and group ID, but how do I get the name?
2 Answers
You can use getgrgid()
to get the group name and getpwuid()
to get the user name:
#include <pwd.h>
#include <grp.h>
/* ... */
struct group *grp;
struct passwd *pwd;
grp = getgrgid(gid);
printf("group: %s\n", grp->gr_name);
pwd = getpwuid(uid);
printf("username: %s\n", pwd->pw_name);
-
Note that
getgrgid()
andgetpwuid()
can returnNULL
if the relevant entry is missing, in which case you should probably just convert the numeric ID to a string withsprintf()
.– cafOct 2, 2011 at 7:03