问题
To get the user name from Windows, using MinGW, should I use the function getlogin() from unistd.h, or the Windows function GetUserName?
Thank you.
回答1:
You can check the USERNAME
variable:
char *name = getenv("USERNAME"); // Get environmentvariable for Username
if( name == NULL )
return -1; // Username not found ...
else
printf("%s\n", name); // Output Username
If you are fully on Windows you can use its API (GetUserName()
) too:
#include <windows.h>
#include <Lmcons.h>
// ...
TCHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
if( GetUserName((TCHAR*) name, &size) )
printf("%s\n", name); // Output Username
else
return -1; // Username not found ...
In general:
- use
getlogin()
if you are on linux / unix since it's not available in MinGW - use
GetUserName()
if you are on windows - use both (conditional group preprocessor) with you want to stay platform independend
来源:https://stackoverflow.com/questions/13612199/how-to-get-the-username-in-mingw