Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine that two Win32 API handles represent the same object?

Tags:

c++

winapi

handle

Suppose I have two hanldes:

HANDLE h1;
HANDLE h2;

And both have received values resulted from some Windows API function - in particular, I'm interesed in handles resulted from calls to CreateFile(). How do I determine that h1 and h2 reference the same underlying object - in the case of CreateFile() - same file, directory or device? Is there some API to determine that?

like image 430
ivan.ukr Avatar asked Apr 03 '15 17:04

ivan.ukr


1 Answers

The GetFileInformationByHandle API returns information that can be used to uniquely identify the referenced object:

You can compare the VolumeSerialNumber and FileIndex members returned in the BY_HANDLE_FILE_INFORMATION structure to determine if two paths map to the same target; for example, you can compare two file paths and determine if they map to the same directory.

For example:

bool SameFile( HANDLE h1, HANDLE h2 ) {
    BY_HANDLE_FILE_INFORMATION bhfi1 = { 0 };
    BY_HANDLE_FILE_INFORMATION bhfi2 = { 0 };
    if ( ::GetFileInformationByHandle( h1, &bhfi1 ) &&
         ::GetFileInformationByHandle( h2, &bhfi2 ) ) {
        return ( ( bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh ) &&
                 ( bhfi1.nFileIndexLow  == bhfi2.nFileIndexLow ) &&
                 ( bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber ) );
    }
    return false;
}
like image 77
IInspectable Avatar answered Sep 23 '22 18:09

IInspectable