简体   繁体   中英

Qt safely remove a device

I'm look for a way to safely remove my USB key from my Qt 5.2 application but I can't find any Qt module to do that.

Is their a way to do it or do I have to hardcode it ?

I've never removed USB using Qt but this simple c code will also work.

#include <sys/mount.h>

int umount(const char *target);

If you mean unmounting your usb device by removal, then there is no cross-platform solution for this. Perhaps there could be added something in the QtSystems module, however the problem is that this would require admin permission or some tricks, eg setuid or caps on Linux and so on.

You could do something along these lines to achieve this feature for now on your side:

void MyClass::unmount() {
#ifdef Q_OS_LINUX
    // See details: http://linux.die.net/man/2/umount
    if (umount(myUsbKeyPath) < 0)
        qDebug() << "Failed to umount";
#elif Q_OS_WIN
    // See details: http://support.microsoft.com/default.aspx?scid=kb;en-us;165721
    DWORD dwBytesReturned;
    DeviceIoControl(hVolume,
                    IOCTL_STORAGE_EJECT_MEDIA,
                    NULL, 0,
                    NULL, 0,
                    &dwBytesReturned,
                    NULL);
#endif
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM