个时候我们需要区分系统磁盘中,哪些是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 = ; char disk_path[] = {};
char device_path[] = {};
DWORD all_disk = GetLogicalDrives();
printf("System volume flag:0x%X\n", all_disk); int i = ;
DWORD bytes_returned = ;
while (all_disk && usb_disk_cnt < cnt)
{
if ((all_disk & 0x1) == )
{
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 >> ;
i++;
} return usb_disk_cnt;
}
调用函数
int _tmain(int argc, _TCHAR* argv[])
{
char usb_volume[] = {};
int usb_cnt = enum_usb_disk(usb_volume, );
printf("System has %d usb disk, their volume are:", usb_cnt);
for (int i = ; i < usb_cnt; i++)
{
printf("%c: ", usb_volume[i]);
} return ;
}
运行结果: