在我的以下代码中:
while((grp = getgrent()) != NULL)
{
if(belong_to(username,grp->gr_mem) || strcmp(username,grp->gr_name) == 0)
{
ugs[counter] = grp->gr_name;
printf("%s",ugs[counter]);
counter++;
putchar('\n');
}
}
while 循环退出后,我得到的 ugs 字符串数组等于 grp->gr_name 值
,这破坏了我正在尝试基本上填满 ugs 数组的整个想法基于条件。
我该如何解决?所以我在那个 if 条件时刻只是一个 grp->gr_name
的值。
最佳答案
好的 - 这是一个可能对此有所帮助的完整示例,以及您的 other post :
测试.c:
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
char * list_members(char **members, char *buff);
int main()
{
int n_grentries = 0, n_pwentries = 0;
struct group *group;
struct passwd *passwd;
char buff[80];
while((group = getgrent()) != NULL) {
n_grentries++;
printf("Group name: %s, ID: %d, members: %s\n",
group->gr_name, group->gr_gid, list_members(group->gr_mem, buff));
}
endgrent();
while((passwd = getpwent()) != NULL) {
n_pwentries++;
printf("User name: %s, UID: %d, shell: %s\n",
passwd->pw_name, passwd->pw_uid, passwd->pw_shell);
}
endpwent();
printf("There are %d groups and %d users on the system.\n",
n_grentries, n_pwentries);
return 0;
}
char * list_members(char **members, char *buff)
{
buff[0] = '\0';
while (members && *members) {
if (*buff)
strcat (buff, ", ");
strcat (buff, *members);
members++;
}
return buff;
}
示例输出:
Group name: root, ID: 0, members: paulsm,
Group name: daemon, ID: 1, members:
Group name: bin, ID: 2, members:
Group name: adm, ID: 4, members: syslog, paulsm,
...
User name: root, UID: 0, shell: /bin/bash
User name: daemon, UID: 1, shell: /usr/sbin/nologin
User name: bin, UID: 2, shell: /usr/sbin/nologin
User name: sys, UID: 3, shell: /usr/sbin/nologin
...
There are 72 groups and 45 users on the system.
关于c - 如何让字符串数组的值不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165580/