個時候我們需要區分系統磁碟中,哪些是U盤,這樣我們在訪問的時候可以區別對待。具體方法如下:
1,呼叫GetLogicalDrives()返回系統碟符標記位
API GetLogicalDrives()將返回一個DWORD型別的標記值,將其轉換成二進位制之後,為1的位標識對應的碟符在系統中存在。比如返回值為:11100,則表示碟符C:D:E:在系統中存在,因為最低位對應碟符A。
2,呼叫GetDriveType()返回磁碟屬性
如果該API返回DRIVE_REMOVABLE,則認為該碟符對應的裝置是USB裝置(U盤或者行動硬碟)
具體程式碼如下:
列舉系統USB磁碟函式
int enum_usb_disk(char usb_paths[], int cnt) { int usb_disk_cnt = 0; char disk_path[5] = {0}; char device_path[10] = {0}; DWORD all_disk = GetLogicalDrives(); printf("System volume flag:0x%X\n", all_disk); int i = 0; DWORD bytes_returned = 0; while (all_disk && usb_disk_cnt < cnt) { if ((all_disk & 0x1) == 1) { sprintf_s(disk_path, "%c:", 'A'+i); sprintf_s(device_path, "\\\\.\\%s", disk_path); if (GetDriveTypeA(disk_path) == DRIVE_REMOVABLE) { usb_paths[usb_disk_cnt++] = 'A' + i; } } all_disk = all_disk >> 1; i++; } return usb_disk_cnt; }
呼叫函式
int _tmain(int argc, _TCHAR* argv[]) { char usb_volume[8] = {0}; int usb_cnt = enum_usb_disk(usb_volume, 8); printf("System has %d usb disk, their volume are:", usb_cnt); for (int i = 0; i < usb_cnt; i++) { printf("%c: ", usb_volume[i]); } return 0; }
執行結果: