Copy directory using Qt

前端 未结 7 1286
迷失自我
迷失自我 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:49

    I wanted something similar, and was googling (in vain), so this is where I've got to:

    static bool cpDir(const QString &srcPath, const QString &dstPath)
    {
        rmDir(dstPath);
        QDir parentDstDir(QFileInfo(dstPath).path());
        if (!parentDstDir.mkdir(QFileInfo(dstPath).fileName()))
            return false;
    
        QDir srcDir(srcPath);
        foreach(const QFileInfo &info, srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
            QString srcItemPath = srcPath + "/" + info.fileName();
            QString dstItemPath = dstPath + "/" + info.fileName();
            if (info.isDir()) {
                if (!cpDir(srcItemPath, dstItemPath)) {
                    return false;
                }
            } else if (info.isFile()) {
                if (!QFile::copy(srcItemPath, dstItemPath)) {
                    return false;
                }
            } else {
                qDebug() << "Unhandled item" << info.filePath() << "in cpDir";
            }
        }
        return true;
    }
    

    It uses an rmDir function that looks pretty similar:

    static bool rmDir(const QString &dirPath)
    {
        QDir dir(dirPath);
        if (!dir.exists())
            return true;
        foreach(const QFileInfo &info, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
            if (info.isDir()) {
                if (!rmDir(info.filePath()))
                    return false;
            } else {
                if (!dir.remove(info.fileName()))
                    return false;
            }
        }
        QDir parentDir(QFileInfo(dirPath).path());
        return parentDir.rmdir(QFileInfo(dirPath).fileName());
    }
    

    This doesn't handle links and special files, btw.

提交回复
热议问题