GetLastError

DWORD GetLastError(void);

The GetLastError function retrieves the last error code set by the calling thread. Error codes are a 32-bit value that can be returned by various system and API functions.

Return Value

The return value is the last error code set by the calling thread. A return value of 0 is not a valid error code. If the last error code for the calling thread has not been set, the return value is 0.

Remarks

Applications call the GetLastError function immediately after any function call that might fail, to obtain information about the error that occurred. Subsequent calls to GetLastError will return a different error code or 0. This is because some functions call GetLastError internally and overwrite the calling thread's last error code.

The error code is stored on a thread-local basis, so that each thread maintains its own independent set of error codes. If multiple threads call this function, each thread receives its own last error value.

The system does not update the last error code when a function call succeeds. If the last error code is potentially useful, the application should save it.

The values for error codes are defined in winerror.h.

See Also

Example

The following example attempts to open a non-existent file, and then displays the last error code and its corresponding descriptive message.

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

int main() {
    HANDLE hFile;
    DWORD dwError;
    LPVOID lpMsgBuf;

    // Attempt to open a file that does not exist
    hFile = CreateFile(
        "non_existent_file.txt", // File name
        GENERIC_READ,            // Access mode
        0,                       // Share mode
        NULL,                    // Security attributes
        OPEN_EXISTING,           // Creation disposition
        FILE_ATTRIBUTE_NORMAL,   // File attributes
        NULL                     // Template file
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        dwError = GetLastError(); // Get the error code

        // Format the error message
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dwError,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0, NULL );

        // Display the error code and message
        printf("Failed to open file.\n");
        printf("Error Code: %lu\n", dwError);
        printf("Error Message: %s\n", (LPCTSTR)lpMsgBuf);

        // Free the buffer
        LocalFree(lpMsgBuf);
    } else {
        printf("File opened successfully (this should not happen).\n");
        CloseHandle(hFile);
    }

    return 0;
}