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

c++, linux, posix, winapi

Solution

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.

Problem

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

Original source