tags:

views:

436

answers:

3

This is a few questions compiled into one post.

1) What would be the best way to tell if a USB mass storage device is plugged in.

2) What is the best way to write data to a USB drive

3) Can you treat the memory on a usb drive as you would in regular memory.. (Could I use like malloc and or write directly two it with values/ and or zero it out?)

+6  A: 

A USB drive appears as a drive letter. You can detect that it might be a USB device using the GetDriveType API. However, this only tells you that it's removable, not that it's actually a USB drive. To tell that, you might need to look at the SetupDiGetDeviceRegistryProperty function (referenced from the GetDriveType MSDN reference). Also, it's possible to have disks mounted that are not drive letters, or drive letters that do not represent disk mounts, so to find all the USB drives, you'd want to look at some of the other SetupDi... functions.

Becuase it is a drive letter, the usual way of reading and writing to a USB drive is to use file-system functions, such as fopen or the Windows CreateFile. If you want to write directly to it as you would memory, you can create a file that spans the whole device, then memory-map the file. However, I wouldn't recommend that except in specialised applications, because if there is an I/O error (including e.g. the user unplugging the drive), then your program will get a SEH exception, and that introduces a lot of complications that are best avoided.

Doug
A: 

Check out this snippet

Josh Stodola
A: 

You might want to have a peek at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR. It tells you which USB storage devices are known. The entries all contain a ParentIdPrefix. If the drive is currently present, that can be found in the data part of a HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices value.

MSalters