Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file's owner name in Linux using C++?

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?

like image 733
Dula Avatar asked Sep 07 '11 02:09

Dula


People also ask

How do I find out the owner of a file in Linux?

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).

What is file owner in Linux?

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.

How do you change a file's owner?

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.

How do you change the owner of all files in a folder in Linux?

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.


2 Answers

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
like image 162
Jonathan Leffler Avatar answered Sep 19 '22 21:09

Jonathan Leffler


One way would be to use stat() to get the uid of a file and then getpwuid() to get the username as a string.

like image 44
jedwards Avatar answered Sep 20 '22 21:09

jedwards