Windows API Reference

File I/O

CreateDirectory

The CreateDirectory function creates a new directory with the specified path. If the directory already exists, the function fails and returns FALSE.

Syntax

BOOL CreateDirectory(
  LPCTSTR lpPathName,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

Parameters

Parameter Type and Description Notes
lpPathName LPCTSTR
The path of the directory to be created. This string can be a name composed of characters that are valid for directory and file names. It can also be a Unicode (WCHAR) or an ANSI string.
Required. The maximum string size for a path is MAX_PATH, which is 260 characters. Use \\?\C:\verylongpath to specify a path longer than 260 characters.
lpSecurityAttributes LPSECURITY_ATTRIBUTES
A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the new directory. If this parameter is NULL, the directory gets a default security descriptor that is the same as the directory or process that created it.
Optional.

Return Value

Return Value Description Conditions
TRUE The directory was created successfully. Success.
FALSE The directory was not created. To get extended error information, call GetLastError. Failure.

Remarks

Example

#include <windows.h>
#include <iostream>

int main() {
    const char* dirName = "C:\\MyNewDirectory";

    if (CreateDirectory(dirName, NULL)) {
        std::cout << "Directory '" << dirName << "' created successfully." << std::endl;
    } else {
        DWORD error = GetLastError();
        if (error == ERROR_ALREADY_EXISTS) {
            std::cout << "Directory '" << dirName << "' already exists." << std::endl;
        } else {
            std::cerr << "Failed to create directory. Error code: " << error << std::endl;
        }
    }

    return 0;
}

Requirements

Header: winbase.h (include windows.h)

Library: Kernel32.lib

Minimum supported client: Windows XP

Minimum supported server: Windows Server 2003