LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

[C++] 特殊フォルダのパスを取得する

Last updated at Posted at 2020-11-25

もくじ
https://qiita.com/tera1707/items/4fda73d86eded283ec4f

やりたいこと

C++のプログラムで「デスクトップ」とか、「Program Files」とかのパスを取得したい。

SHGetKnownFolderPath

SHGetKnownFolderPath()で特殊パスを取得する。

#include <shlobj.h>
#include <iostream>

int main()
{
    WCHAR* path = nullptr;

    auto hr = SHGetKnownFolderPath(FOLDERID_Desktop, KF_FLAG_DEFAULT, NULL, &path);

    if (SUCCEEDED(hr)) {
        std::wcout << path << std::endl;
    }

    CoTaskMemFree(path);
}

取得できるフォルダは、下記を参照

出力

C:\Users\username\Desktop

SHGetSpecialFolderPath(非推奨)

SHGetSpecialFolderPath()関数を使って実現はできるが、現在(2024/01時点)は非推奨らしい。

#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <tchar.h>
#include <iostream>
#include <string>
#include <shlobj.h>// SHGetSpecialFolderPathに必要

int main()
{
    TCHAR waFolderPath[MAX_PATH];

    // CSIDL_DESKTOPのところを変えると、いろんなフォルダが取れる
    SHGetSpecialFolderPath(NULL, waFolderPath, CSIDL_DESKTOP, 0);
    std::wcout << TEXT("CSIDL_DESKTOP                 : ") << waFolderPath << std::endl;

    system("pause");
}

CSIDL_DESKTOPの部分を何に変えるか、は、下記を参照。
https://docs.microsoft.com/en-us/windows/win32/shell/csidl

参考

SHGetKnownFolderPath 関数 (shlobj_core.h)

KNOWNFOLDERID

Windowsの特殊フォルダのパスを取得する
https://www.wabiapp.com/WabiSampleSource/windows/sh_get_special_folder_path.html

SHGetSpecialFolderPathに設定できるCSIDL
http://yamatyuu.net/computer/program/sdk/base/SHGetSpecialFolderPath/csidl.html

CSIDL(MSDocs)
https://docs.microsoft.com/en-us/windows/win32/shell/csidl

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up