Copy directory using Qt

前端 未结 7 1239
迷失自我
迷失自我 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 06:00

    Try this:

    bool copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
    {
        QDir sourceDir(fromDir);
        QDir targetDir(toDir);
        if(!targetDir.exists()){    /* if directory don't exists, build it */
            if(!targetDir.mkdir(targetDir.absolutePath()))
                return false;
        }
    
        QFileInfoList fileInfoList = sourceDir.entryInfoList();
        foreach(QFileInfo fileInfo, fileInfoList){
            if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
                continue;
    
            if(fileInfo.isDir()){    /* if it is directory, copy recursively*/
                if(!copyDirectoryFiles(fileInfo.filePath(),  
                    targetDir.filePath(fileInfo.fileName()), 
                    coverFileIfExist)) 
                    return false;
            }
            else{            /* if coverFileIfExist == true, remove old file first */
                if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
                    targetDir.remove(fileInfo.fileName());
                }
    
                // files copy
                if(!QFile::copy(fileInfo.filePath(),  
                    targetDir.filePath(fileInfo.fileName()))){ 
                        return false;
                }
            }
        }
        return true;
    }
    

提交回复
热议问题