Domanda

I want to know if there is any alternate C library for the unix command groups,

$ groups ---- lists all the group id's of the user.

There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.

È stato utile?

Soluzione

#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);

Altri suggerimenti

Here is a example of how to do it using getgrouplist, feel free to ask anything.

__uid_t uid = getuid();//you can change this to be the uid that you want

struct passwd* pw = getpwuid(uid);
if(pw == NULL){
    perror("getpwuid error: ");
}

int ngroups = 0;

//this call is just to get the correct ngroups
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
__gid_t groups[ngroups];

//here we actually get the groups
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);


//example to print the groups name
for (int i = 0; i < ngroups; i++){
    struct group* gr = getgrgid(groups[i]);
    if(gr == NULL){
        perror("getgrgid error: ");
    }
    printf("%s\n",gr->gr_name);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top