如何在 C/C++ 中以编程方式找到 "Saved Games" 文件夹?

How to find the "Saved Games" folder programmatically in C/C++?

我正在写游戏。我打算将存档存储在 "saved games" 目录中。

如何以编程方式找到 Saved Games 文件夹的位置?

它需要处理非英语 Windows。 %USERPROFILE%\Saved Games 之类的黑客不是一种选择。

保存的游戏目录可以使用 SHGetKnownFolderPath() 功能定位,自 Windows Vista 和 Windows Server 2008 起可用。

请注意,FOLDERID_SavedGames 参数是一个 C++ 引用。替换为 &FOLDERID_SavedGames 以从 C 代码调用。

在我能找到的第一个在线 MSVC 编译器上测试成功:

https://rextester.com/l/cpp_online_compiler_visual

#define WINVER 0x0600
#define _WIN32_WINNT 0x0600

#include <stdio.h>
#include <shlobj.h>
#include <objbase.h>

#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "ole32.lib")

int main(void)
{
    PWSTR path = NULL;
    HRESULT r;

    r = SHGetKnownFolderPath(FOLDERID_SavedGames, KF_FLAG_CREATE, NULL, &path);
    if (path != NULL)
    {
        printf("%ls", path);
        CoTaskMemFree(path);
    }

    return 0;
}