Search code examples
cusb-flash-drive

How to get a list of all the USB removable storages attatched in the system using C?


I am writing a program that will copy some files in a USB removable storage. So I need a list of all removable storages available. I am using C. Portablity is preferred.


Solution

  • Possibly libusbx

    libusbx is a library that provides generic access to USB devices. As a library, it is meant to be used by developers, to facilitate the development of applications that communicate with USB hardware.

    It is portable: Using a single cross-platform API, it provides access to USB devices on Linux, OS X, Windows and OpenBSD.

    It is user-mode: No special privilege or elevation is required for the application to communicate with a device.

    It is version-agnostic: All versions of the USB protocol, from 1.0 to 3.0 (latest), are supported.

    See libusb_get_device_list

    libusb_context * usb_ctx = NULL;
    
    int main()
    {
    ...
    libusb_init(&usb_ctx);
    ...
    libusb_exit(usb_ctx);
    ...
    } 
    
    some_func()
    {
    ...
    libusb_device **list;
    ssize_t number_of_devices = libusb_get_device_list(usb_ctx, &list);
    ...
    }
    

    (warning I found just this online, I have no personal experience with it, code hasn't been tested, It looks like you need to call libusb_init/libusb_exit before after use see

    *http://libusbx.sourceforge.net/api-1.0/group__lib.html*

    and

    http://libusbx.sourceforge.net/api-1.0/contexts.html.h