Skip to content

Instantly share code, notes, and snippets.

@bruxisma
Last active July 10, 2019 09:03
Show Gist options
  • Save bruxisma/724557ce00f8f093a3c694c07a591191 to your computer and use it in GitHub Desktop.
Save bruxisma/724557ce00f8f093a3c694c07a591191 to your computer and use it in GitHub Desktop.
How to use Shlwapi to find your SavedGames directory on Windows and stop using Documents\My Games in the year 2017
cmake_minimum_required(VERSION 3.14)
project(shlwapi-test)
add_executable(findit test.cxx)
target_compile_options(findit PRIVATE /std:c++latest)
#include <Windows.h>
#include <Shlobj.h>
#include <cstdio>
#include <memory>
struct codeleter {
constexpr codeleter () { }
void operator () (void* ptr) const noexcept {
CoTaskMemFree(ptr);
}
};
auto saved_games (wchar_t** ptr) noexcept {
return SHGetKnownFolderPath(
FOLDERID_SavedGames,
KF_FLAG_DEFAULT, /* Give us the full path */
nullptr, /* access token (unnecessary for us) */
ptr);
}
// C++17
int main () {
wchar_t* str { };
auto result = saved_games(&str);
std::unique_ptr<wchar_t, codeleter> data { str };
if (result != S_OK) {
std::puts("Could not locate SavedGames Directory");
std::exit(EXIT_FAILURE);
}
std::wprintf(L"Saved Games: %s\\", data.get());
}
// C++20
/*int main () {
std::unique_ptr<wchar_t, codeleter> data;
if (auto result = saved_games(std::out_ptr(data)); result != S_OK) {
std::puts("Could not located 'Saved Games' directory");
return EXIT_FAILURE;
}
std::wprintf(L"Saved Games: %s\\", data.get());
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment