LinuxのC言語ライブラリのchownを使ってみる。

chown 関数

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

所有者とグループ引数は名前でなく以下のgetpwnamとgetgrnam関数で得たIDを指定する。

struct passwd *getpwnam(const char *name);
struct group *getgrnam(const char *name);

#include
#include
#include
#include
#include


int my_chown(const char* path, const char* user, const char* group);


int main(){
      int iRet = 0;
      iRet = my_chown("/tmp/hoge.txt", "user1", "group1");

      if(iRet != 0)
            printf("Error: %d\n", iRet);


      return 0;
}


//----------------------------------------------------------------
// Change the owner and group of the specified file
// param1: pathfile File path
// param2: user User name
// param3: group Group name
// return: integer 0 for suucess, -1 for failure
//----------------------------------------------------------------
int my_chown(const char* path, const char* user, const char* group){

      struct passwd *pw;
      struct group *gr;

      pw = getpwnam(user); //Get user's info from /etc/passwd
      gr = getgrnam(group); //Get group's info from /etc/group

      return chown(path, pw->pw_uid, gr->gr_gid); //Change owner
}