How can I get get the owner name and group name of a file on a Linux filesystem using C++? The stat()
call only gives me owner ID and group ID but not the actual name.
-rw-r--r--. 1 john devl 3052 Sep 6 18:10 blah.txt
How can I get 'john' and 'devl' programmatically?
Run ls with the -l flag to show the owner and group-owner of files and directories in the current directory (or in a specific named directory).
Initially, a file's owner is identified by the user ID of the person who created the file. The owner of a file determines who may read, write (modify), or execute the file. Ownership can be changed with the chown command. Every user ID is assigned to a group with a unique group ID.
To start the change of ownership process, activate Windows File Explorer and navigate to the specific file or folder to be changed. Right-click that file and then click the Properties item in the context menu. Click the Security tab to reveal the screen shown in Figure A.
To change ownership of files or directories we use chown command in the Linux system. This command is also available in the IBM i operating system. The chgrp command is also used to change only the group ownership of the file in the Linux system.
Use getpwuid()
and getgrgid()
.
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
struct stat info;
stat(filename, &info); // Error check omitted
struct passwd *pw = getpwuid(info.st_uid);
struct group *gr = getgrgid(info.st_gid);
// If pw != 0, pw->pw_name contains the user name
// If gr != 0, gr->gr_name contains the group name
One way would be to use stat()
to get the uid of a file and then getpwuid()
to get the username as a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With