14

I am implementing the (ls) command on Unix while learning from a book. During the coding part of my implementation of the (ls) command with the (-l) flag, I see that I have to prompt the user and group names of the file. So far I have the user and group IDs from the following lines:

struct stat statBuf;

statBuf.st_uid; //For the user id. 
statBuf.st_gid; //For the group id. 

In the default (ls) command on Unix, the information of the file is printed in such a way that the user name is shown instead of the user id.

Can anyone help me to find the correct methodology to retrieve the user and group names from their IDs?

Matvey Aksenov
  • 3,802
  • 3
  • 23
  • 45
CompilingCyborg
  • 4,760
  • 13
  • 44
  • 61

2 Answers2

27

You use getpwuid to look up the password file entry for a particular UID (which includes the user name, but now not the password itself) and getgrgid to look up the group file entry for a particular GID.

Graham Miln
  • 2,724
  • 3
  • 33
  • 33
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
6

check my code for username:

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

string getUser(uid_t uid)
{
    struct passwd *pws;
    pws = getpwuid(uid);
        return pws->pw_name;
}

for groupname you can use getgrgid.

  • 2
    Your sample has some flaws: There is no `string` type in C. And you do not check for `NULL` pointer that might be returned in case the `uid` is unknown. Apart from that is is essentially the same set of functions that was suggested in Donal Fellows' answer. – Gerhardh Aug 23 '18 at 07:08