C++ 如何在 Windows 中获取当前用户的主目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9542611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:57:43  来源:igfitidea点击:

How to get the current user's home directory in Windows

c++windows

提问by Ullan

How can I get the path to the current User's home directory?

如何获取当前用户主目录的路径?

Ex: In Windows, if the current user is "guest" I need "C:\Users\guest"

例如:在 Windows 中,如果当前用户是“guest”,我需要“C:\Users\guest”

My application will run on most of the Windows versions (XP, Vista, Win 7).

我的应用程序将在大多数 Windows 版本(XP、Vista、Win 7)上运行。

回答by Philipp

Use the function SHGetFolderPath. This function is preferred over querying environment variables since the latter can be modified to point to a wrong location. The documentation contains an example, which I repeat here (slightly adjusted):

使用函数SHGetFolderPath。此函数优于查询环境变量,因为后者可以修改为指向错误的位置。该文档包含一个示例,我在这里重复(略有调整):

#include <Shlobj.h>  // need to include definitions of constants

// .....

WCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path))) {
  ...
}

回答by scibuff

Just use the environment variables, in this particular case you want %HOMEPATH%and combine that with %SystemDrive%

只需使用环境变量,在这种特殊情况下,您需要%HOMEPATH%并将其与%SystemDrive%

http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

回答by Vasily Menshev

I have used %USERPROFILE% to get path the current User's home directory.

我已经使用 %USERPROFILE% 来获取当前用户的主目录的路径。

回答by Alex_13_STo_SWE

Approach 1:

方法一:

#include <Shlobj.h>

std::string desktop_directory(bool path_w)
{
    if (path_w == true)
    {
        WCHAR path[MAX_PATH + 1];
        if (SHGetSpecialFolderPathW(HWND_DESKTOP, path, CSIDL_DESKTOPDIRECTORY, FALSE))
        {
            std::wstring ws(path);
            std::string str(ws.begin(), ws.end());
            return str;
        }
        else return NULL;
    }
}

Approach 2:

方法二:

#include <Shlobj.h>

LPSTR desktop_directory()
{
    static char path[MAX_PATH + 1];
    if (SHGetSpecialFolderPathA(HWND_DESKTOP, path, CSIDL_DESKTOPDIRECTORY, FALSE)) return path;
    else return NULL;
}