Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the user name from the user ID

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?

like image 989
CompilingCyborg Avatar asked Nov 25 '11 11:11

CompilingCyborg


People also ask

Is user name the same as user ID?

User IDs may be University Registry numbers or other identifying numbers or codes assigned to students, whereas a User Name is required for logging in.

How do I find my UID username?

In Linux, the /etc/passwd file stores the user information, such as the user's name, UID, group id (GID), user's home directory, and user's shell. We can get the username by parsing the /etc/passwd file.


2 Answers

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.

like image 54
Donal Fellows Avatar answered Oct 12 '22 01:10

Donal Fellows


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.

like image 45
Sanket Tilotkar Avatar answered Oct 12 '22 01:10

Sanket Tilotkar