简体   繁体   中英

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?

您可以使用getpwuid查找特定UID(包括用户名,但现在不包含密码本身)的密码文件条目,并使用getgrgid查找特定GID的组文件条目。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM