简体   繁体   English

如何从用户ID检索用户名

[英]How to retrieve the user name from the user ID

I am implementing the (ls) command on Unix while learning from a book. 我正在学习一本书的同时在Unix上实现(ls)命令。 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. 在使用(-l)标志执行(ls)命令的编码部分期间,我看到必须提示文件的用户名和组名。 So far I have the user and group IDs from the following lines: 到目前为止,我具有以下几行的用户和组ID:

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. 在Unix上的默认(ls)命令中,文件信息的打印方式是显示用户名而不是用户ID。

Can anyone help me to find the correct methodology to retrieve the user and group names from their IDs? 谁能帮助我找到正确的方法来从其ID中检索用户名和组名?

您可以使用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. 对于组名,您可以使用getgrgid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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