CreateDirectory
BOOL CreateDirectory(
_In_opt_ LPCTSTR lpPathName,
_In_opt_ LPSECURITY_ATTRIBUTES lpAttribute
);
The CreateDirectory function creates a new directory. If the underlying file system supports security on files and directories, the function allows you to specify the security attributes for the new directory.
Parameters
-
lpPathName [In, Optional]
A pointer to a null-terminated string that specifies the path of the directory to be created. This parameter can be an absolute or relative path. If the last operator in the path is a directory separator, the function succeeds. For example, "C:\Temp\" creates the directory "Temp" if "C:\" exists.
This parameter can be
NULLor an empty string. -
lpAttribute [In, Optional]
A pointer to a
SECURITY_ATTRIBUTESstructure that specifies the security attributes for the directory. If this parameter isNULL, the directory receives default security attributes.
Return Value
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
If the directory being created already exists, the function succeeds and returns nonzero.
The maximum path length for CreateDirectory is MAX_PATH characters. To specify a longer path, use the CreateDirectoryEx function.
The lpPathName parameter can specify a UNC path.
Requirements
- SDK: Included in Windows 7, Windows Server 2008 R2, and later operating systems.
- Header: Declared in
windows.h - Library: Use
Kernel32.lib - DLL:
Kernel32.dll
Example Code
#include <windows.h>
#include <iostream>
int main() {
LPCTSTR dirPath = L"C:\\MyNewFolder";
if (CreateDirectory(dirPath, NULL)) {
std::wcout << "Directory created successfully: " << dirPath << std::endl;
} else {
DWORD error = GetLastError();
if (error == ERROR_ALREADY_EXISTS) {
std::wcout << "Directory already exists: " << dirPath << std::endl;
} else {
std::wcerr << "Error creating directory. Error code: " << error << std::endl;
}
}
return 0;
}