Qt 文件夹拷贝

Qt 文件夹拷贝

文件夹的拷贝,需要递归拷贝文件夹内的所有文件,以及子目录下的文件

//source:源目录的路径名     destination:目标目录的路径名
bool SrcAnnotation::copyDir(const QString &source, const QString &destination)
{
    QDir directory(source);
    //如果目标目录不存在,则进行创建
    QDir targetDir(destination);
    if(!targetDir.exists())
    {
        QDir root("/");
        if( !root.mkpath(destination) )
        {
            LOG_ERROR()<<"mkpath "<<destination<<"failed";
            addCommonInfo(QString("mkpath %1 failed").arg(destination));
            return false;
        }
    }

    //如果源目录文件不存在,则返回拷贝失败信息。
    if(!directory.exists())
    {
        LOG_ERROR()<<source<<"is not exist";
        addCommonInfo(QString("%1 is not exist").arg(source));
        return false;
    }
    QString srcPath = QDir::toNativeSeparators(source);
    if (!srcPath.endsWith(QDir::separator()))
        srcPath += QDir::separator();
    QString dstPath = QDir::toNativeSeparators(destination);
    if (!dstPath.endsWith(QDir::separator()))
        dstPath += QDir::separator();

    bool error = false;
    QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
    for (QStringList::size_type i=0; i != fileNames.size(); ++i)
    {
        QApplication::processEvents();
        QString fileName = fileNames.at(i);
        QString srcFilePath = srcPath + fileName;
        QString dstFilePath = dstPath + fileName;
        QFileInfo fileInfo(srcFilePath);
        if (fileInfo.isFile() || fileInfo.isSymLink())
        {
            //如果存在,先删除,否则后面copy时会报错
            QFile file(dstFilePath);
            if( file.exists() )
                file.remove();

            if(!QFile::copy(srcFilePath, dstFilePath) )
            {
                error = true;
            }
        }
        else if (fileInfo.isDir())
        {
            QDir dstDir(dstFilePath);
            dstDir.mkpath(dstFilePath);
            if (!copyDir(srcFilePath, dstFilePath))
            {
                error = true;
            }
        }
    }

    return !error;
}

你可能感兴趣的:(Qt,c++,qt,开发语言)