INVALID_HANDLE_VALUE
The INVALID_HANDLE_VALUE constant is a special value defined in the Windows API.
This constant is used to represent an invalid or nonexistent handle. A handle is an abstract identifier that an application uses to refer to an object managed by the operating system, such as a file, a process, or a thread.
Description
When a function that returns a handle fails, it may return INVALID_HANDLE_VALUE to indicate that the operation was unsuccessful and no valid handle was created. This value is often used in conjunction with the GetLastError function to retrieve more detailed error information.
Specifically, INVALID_HANDLE_VALUE is frequently used by functions that create or open file objects, such as CreateFile. If CreateFile fails to create or open a file, it will return INVALID_HANDLE_VALUE.
Usage Example
Here's a conceptual C++ example demonstrating how INVALID_HANDLE_VALUE might be used:
#include <windows.h>
#include <iostream>
int main() {
HANDLE hFile = CreateFile(
L"non_existent_file.txt", // File name
GENERIC_READ, // Desired access
FILE_SHARE_READ, // Share mode
NULL, // Security attributes
OPEN_EXISTING, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL // Template file
);
if (hFile == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
std::cerr << "Failed to open file. Error code: " << error << std::endl;
// Handle the error appropriately
} else {
std::cout << "File opened successfully. Handle: " << hFile << std::endl;
// Use the handle...
CloseHandle(hFile);
}
return 0;
}
Related Constants and Functions
Important Note
While INVALID_HANDLE_VALUE is commonly used and typically has a value of -1, it is best practice to always compare against the named constant rather than its literal value to ensure compatibility across different Windows versions and configurations.