C++ 获取linux和windows系统的用户名

(1)获取linux系统的用户名:

 通过 struct  passwd *getpwuid(uid_t uid)函数;  该函数返回passwd结构体,此结构体中包含用户名字段
struct  passwd {
char  *pw_name;  /*user name */
char  *pw_passwd;  /*user password */
uid_t pw_uid;  /*user id */
gid_t pw_gid;  /*group id */
char  *pw_gecos;  /*user real name */
char  *pw_dir;  /*home directory */
char  *pw_shell;  /*shell program */
};

(2)获取windows系统的用户名:
通过GetUserName( buffer , &len ) 函数

(3)完整的实例(跨平台):
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3.   
  4. #ifdef linux  
  5.     #include <unistd.h>  
  6.     #include <pwd.h>  
  7. #endif  
  8.   
  9. #ifdef _WIN32  
  10.     #include<Windows.h>  
  11. #endif  
  12.   
  13. std::string getUserName()  
  14. {  
  15. #if defined linux   //linux system  
  16.     uid_t userid;  
  17.     struct passwd* pwd;  
  18.     userid=getuid();  
  19.     pwd=getpwuid(userid);  
  20.     return pwd->pw_name;  
  21.   
  22. #elif defined _WIN32  //windows system  
  23.     const int MAX_LEN = 100;  
  24.     char szBuffer[MAX_LEN];  
  25.     DWORD len = MAX_LEN;  
  26.     if( GetUserName(szBuffer, &len) )     //用户名保存在szBuffer中,len是用户名的长度  
  27.         return szBuffer;  
  28.   
  29. #else  //outher system  
  30.     return "";  
  31. #endif  
  32. }  
  33.   
  34. int main()  
  35. {  
  36.     std::string ss = getUserName();  
  37.     std::cout << ss << std::endl;  
  38.     return 0;  
  39. }  
(4)linux系统上gcc编译运行截图
(5)linux下的四个简单函数介绍:getpid, getppid, getuid, getgid
#include <stdio.h>  
  
int main()  
{  
    printf("pid:%d, ppid:%d, uid:%d, gid:%d\n", getpid(), getppid(), getuid(), getgid());  
    return 0;  
}  
 结果为:
 [taoge@localhost learn_c]$ echo $$
2774
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out 
pid:2898, ppid:2774, uid:501, gid:502

[taoge@localhost learn_c]$ su root
Password: 
[root@localhost learn_c]# echo &&

[root@localhost learn_c]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[root@localhost learn_c]# ./a.out 
pid:2922, ppid:2905, uid:0, gid:0

[root@localhost learn_c]# su taoge
[taoge@localhost learn_c]$ echo $$
2928
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out 
pid:2946, ppid:2928, uid:501, gid:502
[taoge@localhost learn_c]$ 
#include <unistd.h>
#include <pwd.h>

void GetUserAndPid()
{
  uid_t userid;
  struct passwd* pwd;
  userid=getuid();
  pwd=getpwuid(userid);
  FILE *fp = fopen("/home/stamp_temp/ao.log", "ab+");
  fprintf(fp, "user:%s, pid:%d, ppid:%d, uid:%d, gid:%d\n", pwd->pw_name, getpid(), getppid(), getuid(), getgid());
  fclose(fp);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值