gpt4 book ai didi

c - 如何打印所有本地用户的组?

转载 作者:行者123 更新时间:2023-11-30 15:11:33 25 4
gpt4 key购买 nike

我想打印/etc/passwd 中存储的所有用户组。看起来很简单,我只需使用 getpwent() 和 getgrouplist() 即可。我带着这个代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <grp.h>

int main(int argc, char** argv){

struct passwd* user;
int nGroups = 20;
gid_t* groups;
groups = malloc(nGroups * sizeof(gid_t));
struct group* gr;
while(user = getpwent()){
printf("%s : ", user->pw_name);
getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);
int i;
for(i = 0; i < nGroups; ++i){
gr = getgrgid(groups[i]);
if(gr){
printf("%s ", gr->gr_name);
}
}
printf("\n");
}

free(groups);
return 0;
}

它给了我这个输出:

root : root 
daemon : daemon
bin : bin
.
.
.
pulse : pulse root
ricenwind : ricenwind adm root root root root root root
vboxadd : daemon

这显然是错误的,例如使用

groups ricenwind

给我:

ricenwind : ricenwind adm cdrom sudo dip plugdev lpadmin sambashare

最佳答案

如果您阅读the getgrouplist manual page你会看到

Up to *ngroups of these groups are returned in the array groups.

ngroups 参数不仅由函数设置,函数还使用它来了解您为 groups 参数分配了多少个结构。

在调用 getgrouplist 之前,您需要“重置”nGroups 变量,否则将使用上次调用该函数设置的旧值:

nGroups = 20;
getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);

关于c - 如何打印所有本地用户的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com