Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the username of the person executing my program?

How can I get the username of the process owner (the user who is executing my program) in C++?

like image 483
H4cKL0rD Avatar asked Feb 03 '10 02:02

H4cKL0rD


2 Answers

On Mac OSX:

getenv("USER");

On Linux:

getenv("USERNAME");
like image 164
Michael Franzl Avatar answered Sep 22 '22 17:09

Michael Franzl


Windows

GetUserName()

Example:

 char user_name[UNLEN+1];
 DWORD user_name_size = sizeof(user_name);
 if (GetUserName(user_name, &user_name_size))
     cout << "Your user name is: " << user_name << endl;
 else
     /* Handle error */

Linux

Look at getpwuid:

The getpwuid() function shall search the user database for an entry with a matching uid.

The getpwuid() function shall return a pointer to a struct passwd

The struct passwd will contain char *pw_name.

Use getuid to get the user id.

like image 37
Thomas Bonini Avatar answered Sep 19 '22 17:09

Thomas Bonini