(C++) Detecting USB Drive by Thomas Roccia

Created the Sunday 19 March 2023. Updated 1 year ago.

Description:

This code uses the GetLogicalDrives function to retrieve a bitmask of all available drives on the system, and the GetDriveTypeA function to check if each drive is removable. If a removable drive is detected, the code prints its drive letter to the console.

Code

            #include <windows.h>

int main() {
    UINT drives = GetLogicalDrives();
    for (int i = 0; i < 26; i++) {
        if ((drives & (1 << i)) && GetDriveTypeA((char)('A' + i) + ":\\") == DRIVE_REMOVABLE) {
            printf("USB drive detected: %c:\n", 'A' + i);
        }
    }
    return 0;
}