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

标签 c unix

我想打印/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/

相关文章:

c - 指针和整数之间的警告比较

c++ - 服务器套接字编程 TCP 连接地址已被使用

linux - 从文本文件中读取文件名然后创建这些文件?

c - 有没有办法在不使用 void 指针的情况下返回 C 函数中的任何类型?

c - 为什么持有自旋锁时不允许 "sleeping"?

c - 是“长 : 16byte on my system?

unix - zcat 无法正确解压缩文件

unix - chmod 775 在一个文件夹上,但不是该文件夹下的所有文件

c - 虚拟内存系统

c - 如何编写一个 if 语句而不是三个