Microsoft Docs

CloseHandle

Function Closes an open object handle.

Syntax

BOOL CloseHandle(
    HANDLE hObject
);

Parameters

ParameterDescription
hObjectA valid handle to an open object. The handle must have been created by a function such as CreateFile, CreateEvent, OpenProcess, etc.

Return Value

If the function succeeds, the return value is nonzero. If it fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Example

#include <windows.h>
#include <stdio.h>

int main(void) {
    HANDLE hFile = CreateFileA(
        "example.txt",
        GENERIC_READ,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (hFile == INVALID_HANDLE_VALUE) {
        printf("CreateFile failed (error %lu)\\n", GetLastError());
        return 1;
    }

    // Perform I/O operations...

    if (!CloseHandle(hFile)) {
        printf("CloseHandle failed (error %lu)\\n", GetLastError());
        return 1;
    }

    printf("File closed successfully.\\n");
    return 0;
}

See Also