How to get username from user id

I execute the command (ls) on Unix while learning in a book. While coding my implementation of the command (ls) with the flag (- l) , I see that I need to request the names of the users and groups of the file, while I have the user and group identifiers from the following lines:

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

In the default command (ls) on Unix, file information is printed so that the username is displayed instead of the username.

Can someone help me find the right methodology to extract the username and group from their identifiers?

+4
source share
2 answers

You use getpwuid to find the password file entry for a specific UID (which includes the username, but now not the password itself) and getgrgid to search for the entry in the group file for the specific GID.

+12
source

You can use getent to convert the identifier to an entry from the passwd and group databases, and then parse the name.

 $ getent passwd 0 | cut -d ':' -f 1 root $ getent group 0 | cut -d ':' -f 1 root 
-1
source

Source: https://habr.com/ru/post/1383045/


All Articles