GetLastError function

MSDN

Syntax

DWORD GetLastError(void);

Return Value

The return value is the calling thread's last-error code value. The error code is a Win32 error code. If the function succeeds, the return value is zero.

Remarks

The system maintains a separate last-error code for each thread. The SetLastError function can be used to set this value manually. Many Windows API functions set the last-error code upon failure. Call GetLastError immediately after a function fails to obtain extended error information.

The last-error code is not automatically cleared; it remains set until the thread calls SetLastError or another API function overwrites it.

Example

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

int main(void)
{
    HANDLE hFile = CreateFileA(
        "nonexistent.txt",          // file name
        GENERIC_READ,               // desired access
        0,                          // share mode
        NULL,                       // security attributes
        OPEN_EXISTING,              // creation disposition
        FILE_ATTRIBUTE_NORMAL,      // flags and attributes
        NULL);                      // template file

    if (hFile == INVALID_HANDLE_VALUE) {
        DWORD err = GetLastError();
        printf("CreateFile failed. Error %lu\\n", err);
    } else {
        CloseHandle(hFile);
    }
    return 0;
}