SoFunction
Updated on 2025-04-13

Method of using ::SHCreateDirectoryEx function in C++

In C++,::SHCreateDirectoryExis a function provided by the Windows Shell API to create multi-level directories (similar tomkdir -pOrder). With the standard libraryCreateDirectoryDifferently, it can automatically create missing intermediate directories in the path. The following are detailed usage methods and examples:

1. Function prototype and dependencies

#include <>
#include <> // Include header file#pragma comment(lib, "") // Link Shell32 library
int SHCreateDirectoryEx(
  _In_opt_ HWND                hwnd,         // Parent window handle (can be set to NULL)  _In_     LPCTSTR             pszPath,      // The directory path to create  _In_opt_ const SECURITY_ATTRIBUTES *psa    // Security attributes (usually NULL));

Return value

  • 0ERROR_SUCCESS): Created successfully.
  • Nonzero value: Error code (can be passedGetLastError()Get detailed error information).

2. Basic usage examples

Example 1: Create a single-layer directory

#include &lt;&gt;
#include &lt;&gt;
#include &lt;iostream&gt;

int main() {
    LPCWSTR path = L"C:\\MyFolder";  // Wide character path (Unicode)
    int result = ::SHCreateDirectoryEx(
        NULL,        // Parentless window        path,        // Directory path        NULL         // Default security properties    );

    if (result == ERROR_SUCCESS) {
        std::wcout &lt;&lt; L"Catalog created successfully: " &lt;&lt; path &lt;&lt; std::endl;
    } else {
        std::wcerr &lt;&lt; L"Error code: " &lt;&lt; result &lt;&lt; std::endl;
    }

    return 0;
}

Example 2: Create a multi-level directory

LPCWSTR path = L"C:\\Parent\\Child\\Grandchild";  // Automatically create missing directories in the middleint result = ::SHCreateDirectoryEx(NULL, path, NULL);

3. Key considerations

(1) Unicode and multibyte character sets

Recommended Unicode version: The Windows API uses wide characters first by default (WCHAR/LPCWSTR)。

If using multibyte character set (char), explicit conversion paths are required:

LPCSTR pathA = "C:\\MyFolder";
WCHAR pathW[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, pathA, -1, pathW, MAX_PATH);
::SHCreateDirectoryEx(NULL, pathW, NULL);

(2) Path format

useDouble backslash\\orForward slash/As a separator:

LPCWSTR path1 = L"C:/MyFolder/Subdir";  // Forward slashLPCWSTR path2 = L"C:\\MyFolder\\Subdir"; // Double backslash

(3) Error handling

Judging whether it is successful by the return value, combined withGetLastError()Get detailed information:

if (result != ERROR_SUCCESS) {
    DWORD error = ::GetLastError();
    LPWSTR errorMsg = nullptr;
    ::FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        error,
        0,
        (LPWSTR)&amp;errorMsg,
        0,
        NULL
    );
    std::wcerr &lt;&lt; L"mistake: " &lt;&lt; errorMsg &lt;&lt; std::endl;
    ::LocalFree(errorMsg);
}

4. FAQs and Solutions

Problem 1: Insufficient path permissions

  • Performance: Return the error code5ERROR_ACCESS_DENIED)。
  • solve
    • Run the program with administrator privileges (right-click → Run as administrator).
    • Modify the target directory permissions (right-click directory → Properties → Security → Edit permissions).

Issue 2: The path is invalid or contains illegal characters

  • Performance: Return the error code123ERROR_INVALID_NAME)。
  • solve: Check whether the path contains<>:"|?*etc.

Problem 3: Insufficient disk space

  • Performance: Return the error code112ERROR_DISK_FULL)。
  • solve: Clean the disk or select another storage location.

5. Alternatives

(1) Use the standard library <filesystem> (C++17 and above)

#include &lt;filesystem&gt;
namespace fs = std::filesystem;

bool createDirectory(const std::wstring&amp; path) {
    try {
        return fs::create_directories(path);
    } catch (const fs::filesystem_error&amp; e) {
        std::wcerr &lt;&lt; L"mistake: " &lt;&lt; () &lt;&lt; std::endl;
        return false;
    }
}

(2) Use the Boost file system library

#include &lt;boost/&gt;
namespace fs = boost::filesystem;

bool createDirectory(const std::string&amp; path) {
    try {
        return fs::create_directories(path);
    } catch (const fs::filesystem_error&amp; e) {
        std::cerr &lt;&lt; "mistake: " &lt;&lt; () &lt;&lt; std::endl;
        return false;
    }
}

Summarize

  • ::SHCreateDirectoryExIt is an efficient tool for creating multi-level directories under the Windows platform, suitable for scenarios where older systems need to be compatible with legacy systems or directly using the Shell API.
  • Pay attention when usingPath formatCharacter encodingandError handling
  • For new projects, priority is givenC++17's<filesystem>orBoost Library, the code is more concise and cross-platform.

This is the article about how to use ::SHCreateDirectoryEx function in C++. For more related C++ ::SHCreateDirectoryEx content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!