In C++,::SHCreateDirectoryEx
is a function provided by the Windows Shell API to create multi-level directories (similar tomkdir -p
Order). With the standard libraryCreateDirectory
Differently, 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:
-
0
(ERROR_SUCCESS
): Created successfully. - Nonzero value: Error code (can be passed
GetLastError()
Get detailed error information).
2. Basic usage examples
Example 1: Create a single-layer directory
#include <> #include <> #include <iostream> 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 << L"Catalog created successfully: " << path << std::endl; } else { std::wcerr << L"Error code: " << result << 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)&errorMsg, 0, NULL ); std::wcerr << L"mistake: " << errorMsg << std::endl; ::LocalFree(errorMsg); }
4. FAQs and Solutions
Problem 1: Insufficient path permissions
-
Performance: Return the error code
5
(ERROR_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 code
123
(ERROR_INVALID_NAME
)。 -
solve: Check whether the path contains
<
,>
,:
,"
,|
,?
,*
etc.
Problem 3: Insufficient disk space
-
Performance: Return the error code
112
(ERROR_DISK_FULL
)。 - solve: Clean the disk or select another storage location.
5. Alternatives
(1) Use the standard library <filesystem> (C++17 and above)
#include <filesystem> namespace fs = std::filesystem; bool createDirectory(const std::wstring& path) { try { return fs::create_directories(path); } catch (const fs::filesystem_error& e) { std::wcerr << L"mistake: " << () << std::endl; return false; } }
(2) Use the Boost file system library
#include <boost/> namespace fs = boost::filesystem; bool createDirectory(const std::string& path) { try { return fs::create_directories(path); } catch (const fs::filesystem_error& e) { std::cerr << "mistake: " << () << std::endl; return false; } }
Summarize
-
::SHCreateDirectoryEx
It 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 format、Character 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!