簡體   English   中英

在 C 中更改所有者和組?

[英]Change owner and group in C?

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

有沒有辦法在沒有system()函數和 Bash 命令的情況下做到這一點?

要完成答案,在 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");
  }
}

您可以使用chmodfchmodat和/或fchmod系統調用。 所有三個都位於<sys/stat.h>

對於所有權, <unistd.h>chownfchownat

試試man 2 chownman 2 chmod

另請參閱此處此處的文檔。

chown()可以解決問題。

man 2 chown

大多數 C 庫中都有一個chown函數:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM