How to get the username in MinGW?

狂风中的少年 提交于 2019-12-12 03:35:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!