How to retrieve the user name from the user ID

拈花ヽ惹草 提交于 2019-11-27 19:29:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8268316/how-to-retrieve-the-user-name-from-the-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!