基本上,我需要编写C代码,提示用户编写gid,然后搜索具有给定gid的组 如果该组存在,则打印用户名,uid,gid,gecos和主目录 我只能使用系统调用
我编写了以下代码,但我始终认为该小组不存在
#include<unistd.h>
#include<pwd.h>
#include<grp.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
int main(void)
{
struct passwd *pw;
struct group *grp;
gid_t gid;
int dim,i;
write(1,"Inserire il gid da cercare: ",strlen("Inserire il gid da cercare: "));
read(0,&gid,sizeof(gid_t));
write(1,"\nHai inserito il seguente gid: ",strlen("\nHai inserito il seguente gid: "));
write(1,&gid,sizeof(gid));
setgrent();
while((grp=getgrent())!=NULL && gid!=grp->gr_gid){
}
if(grp==NULL)
write(2,"\nIl gruppo inserito non esiste!\n",strlen("\nIl gruppo inserito non esiste!\n"));
else if(gid==grp->gr_gid){
write(1,"\nNome utente= ",strlen("\nNome utente= "));
write(1,pw->pw_name,sizeof(pw->pw_name));
write(1,", ",strlen(", "));
write(1,"Uid= ",strlen("Uid= "));
write(1,&pw->pw_uid,sizeof(pw->pw_uid));
write(1,", ",strlen(", "));
write(1,"Gid= ",strlen("Gid= "));
write(1,&pw->pw_gid,sizeof(pw->pw_gid));
write(1,", ",strlen(", "));
write(1,"Gecos= ",strlen("Gecos= "));
write(1,pw->pw_gecos,sizeof(pw->pw_gecos));
write(1,", ",strlen(", "));
write(1,"Home= ",strlen("Home= "));
write(1,pw->pw_dir,sizeof(pw->pw_dir));
write(1,"\n",strlen("\n"));
}
endgrent();
return 0;
}
答案 0 :(得分:0)
问题在于您如何阅读输入:
read(0,&gid,sizeof(gid_t));
这将读取 文本输入 的二进制表示。
所以,如果您输入例如1250
作为输入,gid
的值为0x31323530
(使用ASCII encoding和小字节序)。
您应该读取字符串并将其转换为整数值。 或 使用标准C函数scanf
:
scanf("%d", &gid);