How do I get the user name of the current user?

后端 未结 6 1523
醉梦人生
醉梦人生 2021-01-14 20:05

I want to access the user name in the Windows using C programming and use that name to create the path to the particular file like \"c:\\users\\john\\Roaming.....and so on\"

6条回答
  •  没有蜡笔的小新
    2021-01-14 21:03

    You can get the name of the current user with GetUserName:

    #include 
    #include 
    #include 
    
    int main()
    {
        char name[UNLEN + 1];
        DWORD cch = UNLEN + 1;
        if (GetUserName(name, &cch))
        {
            char cmd[100 + UNLEN + 1];
            sprintf(cmd, "echo The username is \"%s\"", name); // Silly demo command
            system(cmd);
        }
        return 0;
    }
    

    Use GetUserNameEx if you want the name in a specific format.

    If you need to get the path to a special folder like "My Documents" or "Desktop" you should use the special folder functions like SHGetFolderPath or SHGetKnownFolderPath.

提交回复
热议问题