Change ownership and group in c

I want to change the owner and group of a file in c. I google it, but if you find only some code that uses the system () command and chmod or relative functions. is there any way to do this without system () functions and bash commands?

thank you all. but a new problem !: is there a way to get the uid and gid of the user without using the command "id -u username" in c? parsing / etc / passwd? or better?

+6
source share
5 answers

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

For ownership of chown and fchownat , as in <unistd.h> .

+6
source

To execute the answer, on Linux you can use the following (I tested on Ubuntu ):

 #include <sys/types.h> #include <pwd.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"); } } 
+4
source

Try man 2 chown and man 2 chmod .

Also see the documentation here and here .

+1
source

chown() does the trick.

 man 2 chown 
+1
source

Most C libraries have a chown function:

 #include <sys/types.h> #include <unistd.h> int chown(const char *path, uid_t owner, gid_t group); 
+1
source

Source: https://habr.com/ru/post/905454/


All Articles