当前位置: 技术问答>linux和unix
请问如何在unix/linux环境下编程实现辨别当前程序执行者用户名和系统类型(linux or unix)
来源: 互联网 发布时间:2014-12-11
本文导语: 同上 | //获得用户名,请你在qt下试试看,行不行? int fgetline(FILE *fp,char *buf); int main() { FILE *fp; int uid,ret=1,i; char buf[1024],user[128]; char *p,*q; if( ( fp = fopen("/etc/passwd","r") ) == NULL ){ ...
同上
|
//获得用户名,请你在qt下试试看,行不行?
int fgetline(FILE *fp,char *buf);
int main()
{
FILE *fp;
int uid,ret=1,i;
char buf[1024],user[128];
char *p,*q;
if( ( fp = fopen("/etc/passwd","r") ) == NULL ){
printf("fopen errorn");
return -1;
}
uid = getuid();
printf("uid=%dn",uid);
ret = fgetline(fp,buf);
while(ret!=-1){
q=buf;
i = 0;
while((p=(char *)strtok(q,":"))){
i++;
if( i == 1 ) //第一个域是username
strcpy(user,p);
if( i == 3 )//第三个域是uid
break;
q +=strlen(p)+1;
}
if( atoi(p) == uid ){
puts(user);
break;
}
ret = fgetline(fp,buf);
}
fclose( fp );
return 1;
}
int fgetline(FILE *fp,char *buf)
{
int c=0,count=0;
while(!feof(fp)){
c = fgetc(fp);
if( c == 'n' )
break;
buf[count]=c;
count++;
}
buf[count]='';
if( count
int fgetline(FILE *fp,char *buf);
int main()
{
FILE *fp;
int uid,ret=1,i;
char buf[1024],user[128];
char *p,*q;
if( ( fp = fopen("/etc/passwd","r") ) == NULL ){
printf("fopen errorn");
return -1;
}
uid = getuid();
printf("uid=%dn",uid);
ret = fgetline(fp,buf);
while(ret!=-1){
q=buf;
i = 0;
while((p=(char *)strtok(q,":"))){
i++;
if( i == 1 ) //第一个域是username
strcpy(user,p);
if( i == 3 )//第三个域是uid
break;
q +=strlen(p)+1;
}
if( atoi(p) == uid ){
puts(user);
break;
}
ret = fgetline(fp,buf);
}
fclose( fp );
return 1;
}
int fgetline(FILE *fp,char *buf)
{
int c=0,count=0;
while(!feof(fp)){
c = fgetc(fp);
if( c == 'n' )
break;
buf[count]=c;
count++;
}
buf[count]='';
if( count