I am attempting to get a list of removable/USB drives connected to a Windows computer. I have tried functions like GetLogicalDrives however I have had no luck. I am looking for an effective method of gathering the USB list
-
2Your title and question are a bit different. Do you strictly just want mass storage devices (drives), or do you want *all* USB devices (mice, serial adapters, network devices...)? – David Grayson Apr 09 '22 at 22:58
-
1What does "I have had no luck" mean? Didn't the API return useful information or were you unable to get anything working at all? – Cheatah Apr 09 '22 at 23:14
-
check the accepted answer on this answer... https://stackoverflow.com/questions/3331043/get-list-of-connected-usb-devices – Mashudu M Apr 09 '22 at 23:15
1 Answers
This will do what you asked. It returns all removable drives, meaning that it will returns all USB drives, but also everything tagged as "Removable" by Windows - excepted CD-ROM, they have their own type (see GetDriveType for details).
If you want exclusively USB drives, you'll need to call also SetupDiGetDeviceRegistryPropertyW with SPDRP_REMOVAL_POLICY property before accepting the drive, I've left a comment to where you should insert it if needed.
#include <Windows.h>
#include <fileapi.h>
#include <tchar.h>
// Return a list of removable devices like GetLogicalDrives
// Bit 0=drive A, bit 26=drive Z.
// 1=removable drive, 0=everything else.
DWORD getRemovableDrives()
{
DWORD result = 0u ;
DWORD curr = 0u ;
// Found all existing drives.
if ((curr=GetLogicalDrives())) {
TCHAR root[3] = TEXT("A:") ;
int idx = 1 ;
// Parse drives.
for (int i=0;i<26;i++, idx<<=1) {
// If drive present, check it..
if ( (curr & idx) && (GetDriveType(root)==DRIVE_REMOVABLE) )
// Drive is removable (can be USB, CompactFlash, SDCard, ...).
// Call SetupDiGetDeviceRegistryPropertyW here if needed.
result |= idx ;
root[0]++ ;
}
}
return result ;
}
int main()
{
DWORD removableDrives = getRemovableDrives() ;
int count = 0 ;
_tprintf(TEXT("Current removable drive(s):\n\t")) ;
for (int i=0 ; i<26 ; i++)
if (removableDrives & (1<<i)) {
_tprintf(TEXT("%c: "),_T('A')+i) ;
count++ ;
}
_tprintf(TEXT("\nFound %d removable drive(s).\n"),count) ;
return 0 ;
}
Sample output:
Current removable drive(s):
K: N:
Found 2 removable drive(s).
The main function, getRemovableDrives()
, is obviously fully silent and does not produce any output. The main()
only shows how to parse its results. The function is pretty fast, therefore you can call it without impacting too much performances - but it would be better to get notifications about drives connection/disconnection anyway.
Error checking is at minimal level, and my Unicode C is a bit rusted so they may be some space for some little more optimizations.

- 1,483
- 4
- 13