我正在尝试在我的 UNIX 系统中查找用户所属的所有组,以及每个用户的组。实现必须在 C 中。这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
static void error_fatal(char* msg)
{ perror(msg); exit(EXIT_FAILURE); }
int main(int argc, char** argv) {
struct group* grp;
struct passwd* pwd;
char *name;
int i = 0;
setpwent();
while((pwd = getpwent()) != NULL){
if( ( name = (char*) malloc( (strlen(pwd->pw_name)+1)*sizeof(char))) == NULL ) error_fatal("malloc");
strcpy(name, pwd->pw_name);
printf("%s:\n", name);
setgrent();
while( (grp = getgrent()) != NULL ) {
for( i=0; i < (sizeof(grp->gr_mem)/sizeof(grp->gr_mem[0])); i++ ){
if( /*strlen(&grp->gr_mem[i][0]) == strlen(name) && */ !strcmp(grp->gr_mem[i], name) )
printf("%s\n", name);
} }
endgrent();
free(name);
}
endpwent();
return 0;
}
但是在“root:”输出后出现分段错误。我很确定问题出在访问 /etc/group 文件的第四个字段中的成员列表(有关详细信息,请参见 man 5 group)。
所以,基本上我的问题是找出每个组有多少成员,所以我的计数器(我在程序中,最后一个 for 循环)会有很好的上限。