如何使用 C++ 在 Linux 中获取文件的所有者名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7328327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:03:36  来源:igfitidea点击:

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

c++linuxfile-ownership

提问by Dula

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.

如何使用 C++ 在 Linux 文件系统上获取文件的所有者名称和组名称?该stat()呼叫只给我主人ID和组ID而不是实际的名称。

-rw-r--r--.  1 john devl  3052 Sep  6 18:10 blah.txt

How can I get 'john' and 'devl' programmatically?

我怎样才能以编程方式获得 'john' 和 'devl'?

采纳答案by Jonathan Leffler

Use getpwuid()and getgrgid().

使用getpwuid()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

回答by jedwards

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

一种方法是使用stat()获取文件的 uid,然后getpwuid()将用户名作为字符串获取。