如何使用 C++ 在 Windows 中获取系统文件夹路径(C:\Windows C:\Program Files)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2489613/
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 23:39:02  来源:igfitidea点击:

How To Get System Folder Path(C:\Windows C:\Program Files) in Windows using C++?

c++windowsapimfc

提问by sxingfeng

I am programming in c++ MFC,

我正在用 C++ MFC 编程,

I want to get "C:\windows" "c:\program files" folder path.

我想获得“C:\windows”“c:\program files”文件夹路径。

Sometimes user may setup windows in other folder such as c:\windows0.

有时用户可能会在其他文件夹中设置窗口,例如 c:\windows0。

Is there any API to get absolute path of the windows and program files path?

是否有任何 API 可以获取 Windows 和程序文件路径的绝对路径?

Many thanks!

非常感谢!

回答by Anzurio

Using Win32 API>

使用 Win32 API>

For the Windows folder:

对于 Windows 文件夹:

TCHAR windir[MAX_PATH];
GetWindowsDirectory(windir, MAX_PATH);

For program files:

对于程序文件:

TCHAR pf[MAX_PATH];
SHGetSpecialFolderPath(
    0,
    pf, 
    CSIDL_PROGRAM_FILES, 
    FALSE ); 

Where MAX_PATHcomes from the Windows headers and will guarantee the buffer is long enough for the longest (non-UNC) path.

哪里MAX_PATH来自 Windows 标头,并保证缓冲区对于最长(非 UNC)路径来说足够长。

Also, note that SHGetSpecialFolderPathcan be used to retrieve other "special" folder including the Windows folder just by replacing the third parameter to any from this list.

另请注意,SHGetSpecialFolderPath只需将第三个参数替换为此列表中的任何一个,即可用于检索其他“特殊”文件夹,包括 Windows 文件夹。

回答by Adrian McCarthy

On Vista+, SHGetKnownFolderPathis the replacement for SHGetFolderPathand SHGetSpecialFolderPath, although you can continue to use the older functions if you need backward compatibility to older versions of Windows.

在Vista +,SHGetKnownFolderPath是替代SHGetFolderPathSHGetSpecialFolderPath,虽然可以继续,如果你需要旧版本的Windows向后兼容使用旧的功能。

回答by Joshua

Most of these come from SHGetFolderPath, but GetSystemDirectory() returns the absolute location of C:\Windows\System32. Don't use GetWindowsDirectory(). It doesn't do what you want anymore.

其中大部分来自 SHGetFolderPath,但 GetSystemDirectory() 返回 C:\Windows\System32 的绝对位置。不要使用 GetWindowsDirectory()。它不再做你想做的事了。

回答by Sameer

Call getenv("%ProgramFiles%") and getenv("%WinDir%")

调用getenv("%ProgramFiles%") 和getenv("%WinDir%")