RemoveDirectory Function

The RemoveDirectory function deletes an existing empty directory.

Syntax


BOOL RemoveDirectory(
  [in] LPCTSTR lpPathName
);
            

Parameters

Parameter Type Description
[in] lpPathName LPCTSTR A pointer to a null-terminated string that specifies the path for the directory to be deleted. This parameter can specify a relative path or an absolute path.

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

Note

The behavior of RemoveDirectory with symbolic links may vary depending on the system configuration and the type of symbolic link.

Warning

Attempting to delete a directory that is not empty will result in an error. Ensure that the directory is completely empty before calling this function.

Example


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

int main() {
    const wchar_t* dirToDelete = L"C:\\Temp\\MyEmptyFolder";

    // Create a dummy directory to demonstrate deletion
    if (CreateDirectory(dirToDelete, NULL)) {
        std::wcout << L"Directory created for demonstration: " << dirToDelete << std::endl;
    } else {
        if (GetLastError() != ERROR_ALREADY_EXISTS) {
            std::cerr << "Failed to create directory. Error: " << GetLastError() << std::endl;
            return 1;
        }
    }

    // Attempt to remove the directory
    if (RemoveDirectory(dirToDelete)) {
        std::wcout << L"Directory deleted successfully: " << dirToDelete << std::endl;
    } else {
        std::cerr << "Failed to delete directory. Error: " << GetLastError() << std::endl;
        // Clean up if directory was not empty or other error occurred
        if (GetLastError() == ERROR_DIR_NOT_EMPTY) {
             std::cerr << "The directory is not empty." << std::endl;
        }
    }

    return 0;
}
            

Requirements

Module Header Library
Kernel32.dll Windows.h Kernel32.lib

See Also