Search code examples
c++qtfile-copying

C++ Transfer Files From Qt to External USB Drive


I am new in Qt and I need help in transferring all files from a specific path of the local machine to an external USB Drive.


Solution

  • I have solved the problem with the QStorageInfo::mountedVolumes() which return the list of the devices that are connected to the Machine. But all of them won't have a name except the Pendrive or HDD. So (!(storage.name()).isEmpty())) it will return the path to only those devices.

    QString location;
    QString path1= "/Report/1.txt";
    QString locationoffolder="/Report";
    
    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {
        if (storage.isValid() && storage.isReady() && (!(storage.name()).isEmpty())) {
            if (!storage.isReadOnly()) {
    
               qDebug() << "path:" << storage.rootPath();
               //WILL CREATE A FILE IN A BUILD FOLDER
               location = storage.rootPath();
               QString srcPath = "writable.txt";
               //PATH OF THE FOLDER IN PENDRIVE
               QString destPath = location+path1;
               QString folderdir = location+locationoffolder;
               //IF FOLDER IS NOT IN PENDRIVE THEN IT WILL CREATE A FOLDER NAME REPORT
               QDir dir(folderdir);
               if(!dir.exists()){
                  dir.mkpath(".");
               }
    
               qDebug() << "Usbpath:" <<destPath;
               if (QFile::exists(destPath)) QFile::remove(destPath);
               QFile::copy(srcPath,destPath);
               qDebug("copied");
    
            }
        }
    }
    

    I had to create a folder as well as in USB because of my requirements and I have given a static name for the files. Then I just copied the data from file of the local machine to the file which I have created in USB with the help of QFile::copy(srcPath, dstPath). I hope it will help someone.