CreateDirectory Function

Creates a new directory.

Syntax

BOOL CreateDirectory(
    _In_ LPCTSTR lpPathName,
    _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

Parameters

Parameter Description
lpPathName

The path of the directory to be created. This string must specify the root and one or more directory names. Example: "C:\Temp\NewDir"

The path can be a relative or absolute path.

lpSecurityAttributes

A pointer to a SECURITY_ATTRIBUTES structure that determines the security of the new directory. If this parameter is NULL, the directory gets a default security descriptor.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory. If NULL, the file gets a default security descriptor. The access control list (ACL) is inherited from the parent directory.

Return Value

Value Description
TRUE The directory was created successfully.
FALSE The function failed. To get extended error information, call GetLastError.

Remarks

If the directory already exists, the function succeeds and returns a nonzero value.

If the trailing backslash (\) is omitted from the specified path, the function fails and returns FALSE.

The function creates all intermediate directories in the specified path if they do not exist.

Note: For Unicode and ANSI versions of this function, use CreateDirectoryW and CreateDirectoryA respectively. The generic CreateDirectory uses the default system code page.

Example

// Create a new directory named "MyNewFolder" in the current directory
BOOL success = CreateDirectory(TEXT("MyNewFolder"), NULL);

if (success) {
    MessageBox(NULL, TEXT("Directory created successfully!"), TEXT("Success"), MB_OK);
} else {
    DWORD error = GetLastError();
    // Handle error, e.g., directory already exists, invalid path, etc.
    TCHAR errorMessage[256];
    wsprintf(errorMessage, TEXT("Failed to create directory. Error code: %lu"), error);
    MessageBox(NULL, errorMessage, TEXT("Error"), MB_OK | MB_ICONERROR);
}

Requirements

Header File
Windows.h winbase.h