gpt4 book ai didi

c - 获取用户组 ID,然后打印具有相同组 ID 的用户列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:32 25 4
gpt4 key购买 nike

您好,我正在尝试列出具有与您的用户 ID 相匹配的组 ID 的所有用户名。我正在考虑使用 getpwent 但似乎无法正确使用它似乎得到了一个无限循环而且我不确定回家是否只过滤掉具有相同组名的那些。

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


int main(){
uid_t myId;
myId = getuid();

struct passwd *pPwdInfo = NULL;
pPwdInfo = getpwuid(myId);

if((pPwdInfo = getpwuid(myId)) != NULL){
int gId = pPwdInfo->pw_gid;

struct passwd *pwd_entry = NULL;
pwd_entry = getpwent();

setpwent(); // go to the top of /etc/passwd

while(pwd_entry){
printf("Username: %s\n", pwd_entry->pw_name);
printf("Password: %s\n", pwd_entry->pw_passwd);
printf("User Id: %d\n", pwd_entry->pw_uid);
printf("Group Id: %d\n", pwd_entry->pw_gid);
printf("User info: %s\n", pwd_entry->pw_gecos);
printf("Home Directory: %s\n", pwd_entry->pw_dir);
printf("Shell Program: %s\n", pwd_entry->pw_shell);
}

endpwent();
}else{

}
return 0;
}

最佳答案

根据手册页

The getpwent() function returns a pointer to a structure containing the broken-out fields of a record from the password database (e.g., the local password file /etc/passwd, NIS, and LDAP). The first time getpwent() is called, it returns the first entry; thereafter, it returns successive entries.

所以你忘了在循环内连续调用getpwent()

while(pwd_entry){
if (pwd_entry->pw_gid == uid_you_want_to_match) {
printf("Username: %s\n", pwd_entry->pw_name);
printf("Password: %s\n", pwd_entry->pw_passwd);
printf("User Id: %d\n", pwd_entry->pw_uid);
printf("Group Id: %d\n", pwd_entry->pw_gid);
printf("User info: %s\n", pwd_entry->pw_gecos);
printf("Home Directory: %s\n", pwd_entry->pw_dir);
printf("Shell Program: %s\n", pwd_entry->pw_shell);
}
pwd_entry = getpwent()
}

关于c - 获取用户组 ID,然后打印具有相同组 ID 的用户列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42367581/

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