Ali Azimi
Ali Azimi

Reputation: 331

Change owner and group in C?

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.

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

Upvotes: 16

Views: 27489

Answers (5)

Ani
Ani

Reputation: 1526

To complete the answer, on Linux the following can be used (I've tested on 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");
  }
}

Upvotes: 16

wildplasser
wildplasser

Reputation: 44250

chown() does the trick.

man 2 chown

Upvotes: 1

Employed Russian
Employed Russian

Reputation: 213764

Try man 2 chown and man 2 chmod.

Also see documentation here and here.

Upvotes: 1

Mat
Mat

Reputation: 206841

You can use the chmod, fchmodat and/or fchmod system calls. All three are located in <sys/stat.h>.

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

Upvotes: 10

Ted Hopp
Ted Hopp

Reputation: 234847

There is a chown function in most C libraries:

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

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

Upvotes: 1

Related Questions