Copy directory using Qt

前端 未结 7 1300
迷失自我
迷失自我 2020-12-29 05:08

I want to copy a directory from one drive to another drive. My selected directory contains many sub directories and files.

How can I implement the same using Qt?

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 05:34

    This is basically petch's answer with a slight change due to it breaking for me in Qt 5.6 (this is the top question hit), so all credit goes to petch.

    function

    bool copyPath(QString sourceDir, QString destinationDir, bool overWriteDirectory)
    {
        QDir originDirectory(sourceDir);
    
        if (! originDirectory.exists())
        {
            return false;
        }
    
        QDir destinationDirectory(destinationDir);
    
        if(destinationDirectory.exists() && !overWriteDirectory)
        {
            return false;
        }
        else if(destinationDirectory.exists() && overWriteDirectory)
        {
            destinationDirectory.removeRecursively();
        }
    
        originDirectory.mkpath(destinationDir);
    
        foreach (QString directoryName, originDirectory.entryList(QDir::Dirs | \
                                                                  QDir::NoDotAndDotDot))
        {
            QString destinationPath = destinationDir + "/" + directoryName;
            originDirectory.mkpath(destinationPath);
            copyPath(sourceDir + "/" + directoryName, destinationPath, overWriteDirectory);
        }
    
        foreach (QString fileName, originDirectory.entryList(QDir::Files))
        {
            QFile::copy(sourceDir + "/" + fileName, destinationDir + "/" + fileName);
        }
    
        /*! Possible race-condition mitigation? */
        QDir finalDestination(destinationDir);
        finalDestination.refresh();
    
        if(finalDestination.exists())
        {
            return true;
        }
    
        return false;
    }
    

    Use:

    /*! Overwrite existing directories. */
    bool directoryCopied = copyPath(sourceDirectory, destinationDirectory, true);
    
    /*! Do not overwrite existing directories. */
    bool directoryCopied = copyPath(sourceDirectory, destinationDirectory, false);
    

提交回复
热议问题