Copy directory using Qt

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

    Manually, you can do the next things:

    1). with func below you generate folders/files list (recursively) - the destination files.

    static void recurseAddDir(QDir d, QStringList & list) {
    
        QStringList qsl = d.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
    
        foreach (QString file, qsl) {
    
            QFileInfo finfo(QString("%1/%2").arg(d.path()).arg(file));
    
            if (finfo.isSymLink())
                return;
    
            if (finfo.isDir()) {
    
                QString dirname = finfo.fileName();
                QDir sd(finfo.filePath());
    
                recurseAddDir(sd, list);
    
            } else
                list << QDir::toNativeSeparators(finfo.filePath());
        }
    }
    

    2). then you may to start copying files from destination list to the new source directory like that:

    for (int i = 0; i < gtdStringList.count(); i++) {
    
        progressDialog.setValue(i);
        progressDialog.setLabelText(tr("%1 Coping file number %2 of %3 ")
            .arg((conf->isConsole) ? tr("Making copy of the Alta-GTD\n") : "")
            .arg(i + 1)
            .arg(gtdStringList.count()));
    
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
    
        if (progressDialog.wasCanceled()) {
    
            // removing tmp files/folders
            rmDirectoryRecursive(tmpFolder);
            rmDirectoryRecursive(tmpFolderPlus);
            setEnableGUI(true);
            return;
        }
    
        // coping
        if (!QFile::copy(gtdStringList.at(i), tmpStringList.at(i))) {
    
            if (warningFlag) {
    
                QMessageBox box(this);
                QString name = tr("Question");
                QString file1 = getShortName(gtdStringList.at(i), QString("\\...\\"));
                QString file2 = getShortName(tmpStringList.at(i), QString("\\...\\"));
                QString text = tr("Cannot copy %1 

    to %2" \ "

    This file will be ignored, just press Yes button" \ "

    Press YesToAll button to ignore other warnings automatically..." \ "

    Or press Abort to cancel operation").arg(file1).arg(file2); box.setModal(true); box.setWindowTitle(name); box.setText(QString::fromLatin1("%1").arg(text)); box.setIcon(QMessageBox::Question); box.setStandardButtons(QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::Abort); switch (box.exec()) { case (QMessageBox::YesToAll): warningFlag = false; break; case (QMessageBox::Yes): break; case (QMessageBox::Abort): rmDirectoryRecursive(tmpFolder); rmDirectoryRecursive(tmpFolderPlus); setEnableGUI(true); return; } } } }

    And that's all. Good luck!

提交回复
热议问题