Linux 在 C 中更改所有者和组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8778834/
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
Change owner and group in C?
提问by Ali Azimi
I want to change owner and group of a file in C. I google it, but if find only some code that use system()
and chmod
command or relative functions.
我想在 C 中更改文件的所有者和组。我用谷歌搜索它,但如果只找到一些使用system()
和chmod
命令或相关函数的代码。
Is there a way to do this without system()
functions and Bash commands?
有没有办法在没有system()
函数和 Bash 命令的情况下做到这一点?
采纳答案by Mat
回答by Employed Russian
回答by wildplasser
chown()
does the trick.
chown()
诀窍。
man 2 chown
回答by Ted Hopp
回答by vyom
To complete the answer, on Linux the following can be used (I've tested on Ubuntu
):
要完成答案,在 Linux 上可以使用以下内容(我已经在 上测试过Ubuntu
):
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
void do_chown (const char *file_path,
const char *user_name,
const char *group_name)
{
uid_t uid;
gid_t gid;
struct passwd *pwd;
struct group *grp;
pwd = getpwnam(user_name);
if (pwd == NULL) {
die("Failed to get uid");
}
uid = pwd->pw_uid;
grp = getgrnam(group_name);
if (grp == NULL) {
die("Failed to get gid");
}
gid = grp->gr_gid;
if (chown(file_path, uid, gid) == -1) {
die("chown fail");
}
}