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

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

Change owner and group in C?

clinuxchown

提问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 chmodcommand or relative functions.

我想在 C 中更改文件的所有者和组。我用谷歌搜索它,但如果只找到一些使用system()chmod命令或相关函数的代码。

Is there a way to do this without system()functions and Bash commands?

有没有办法在没有system()函数和 Bash 命令的情况下做到这一点?

采纳答案by Mat

You can use the chmod, fchmodatand/or fchmodsystem calls. All three are located in <sys/stat.h>.

您可以使用chmod,fchmodat和/或fchmod系统调用。这三个都位于<sys/stat.h>.

For ownership, there's chownand fchownat, both in <unistd.h>.

对于所有权,在chownfchownat中都有<unistd.h>

回答by Employed Russian

Try man 2 chownand man 2 chmod.

尝试man 2 chownman 2 chmod

Also see documentation hereand here.

另请参阅此处此处的文档。

回答by wildplasser

chown()does the trick.

chown()诀窍。

man 2 chown

回答by Ted Hopp

There is a chownfunction in most C libraries:

chown大多数C库中都有一个函数:

#include <sys/types.h>
#include <unistd.h>

int chown(const char *path, uid_t owner, gid_t group);

回答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");
  }
}