c++portabilitygetenv

Portable way to get user name


For C/C++ there seems to be no portable function to get the user name in Linux/Posix and Windows. What would be the least cumbersome and yet robust portable code to achieve this ?

In Linux the USER environment variable seems always to be defined, whereas Windows seems to define the USERNAME variable. Relying on getenv one could avoid including windows.h and minimize preprocessor statements:

char * user_name = getenv("USER");
if (!user_name) {
     user_name = getenv("USERNAME");
}

But is this approach halfway robust ? Or am I ignorant to another solution ? And I was also ignorant towards iOS ...


Solution

  • There is no portable solution.

    Under Linux (and Unix in general), a "user" is a number, and can have several different names. Use getuid to get the id, then getpwuid to get one of the names. Or use getlogin to get the name the user used to login (but this will only work if the process has a controlling terminal). If you want to get all of the names the user is known under, you'll have to iterate using getpwent, checking the pw_uid field for each entry returned.

    The use of an environment variable is not guaranteed. In many contexts, the environment variable won't be set, and even if it is, it's not guaranteed to be correct.

    Windows has a function GetUserName; I don't know too much about it, however.