Qt递归拷贝和删除目录

       最近在翻看项目代码时,看到了这两个函数,想到这个功能十分常用,因此拿出来与大家分享,希望对大家有用。几点说明:

1、记得当初写代码那会,是参考了网上的帖子写的,做了一点小修改。因此代码源于网络。

2、同时感谢原作者,只可惜当时没能记下原文网址,实在抱歉!刚才搜了一下,也没搜着,大家若发现原文出处,请跟帖提醒。谢谢!

3、到目前为止,代码在项目中测试、运行正常,大家若使用时发现Bug,请跟帖指出,我待验证后会及时修改更新。谢谢!

bool copyDir(const QString &source, const QString &destination, bool override)
{
    QDir directory(source);
    if (!directory.exists())
    {
        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)
    {
        QString fileName = fileNames.at(i);
        QString srcFilePath = srcPath + fileName;
        QString dstFilePath = dstPath + fileName;
        QFileInfo fileInfo(srcFilePath);
        if (fileInfo.isFile() || fileInfo.isSymLink())
        {
            if (override)
            {
                QFile::setPermissions(dstFilePath, QFile::WriteOwner);
            }
            QFile::copy(srcFilePath, dstFilePath);
        }
        else if (fileInfo.isDir())
        {
            QDir dstDir(dstFilePath);
            dstDir.mkpath(dstFilePath);
            if (!copyDir(srcFilePath, dstFilePath, override))
            {
                error = true;
            }
        }
    }

    return !error;
}


 QtCreator版本(在阅读 QtCreator 源码时,看到一个和以上功能一样的函数,想必像QtCreator这样的项目代码质量比我等程序员的代码质量更高。因此,特摘抄下来已做更新):

// taken from utils/fileutils.cpp. We can not use utils here since that depends app_version.h.
static bool copyRecursively(const QString &srcFilePath,
                            const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        targetDir.cdUp();
        if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
            return false;
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath
                    = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath
                    = tgtFilePath + QLatin1Char('/') + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath))
                return false;
        }
    } else {
        if (!QFile::copy(srcFilePath, tgtFilePath))
            return false;
    }
    return true;
}


 

bool deleteDir(const QString &dirName)
{
    QDir directory(dirName);
    if (!directory.exists())
    {
        return true;
    }

    QString srcPath = QDir::toNativeSeparators(dirName);
    if (!srcPath.endsWith(QDir::separator()))
        srcPath += QDir::separator();

    QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
    bool error = false;
    for (QStringList::size_type i=0; i != fileNames.size(); ++i)
    {
        QString filePath = srcPath + fileNames.at(i);
        QFileInfo fileInfo(filePath);
        if (fileInfo.isFile() || fileInfo.isSymLink())
        {
            QFile::setPermissions(filePath, QFile::WriteOwner);
            if (!QFile::remove(filePath))
            {
                qDebug() << "remove file" << filePath << " faild!";
                error = true;
            }
        }
        else if (fileInfo.isDir())
        {
            if (!deleteDir(filePath))
            {
                error = true;
            }
        }
    }

    if (!directory.rmdir(QDir::toNativeSeparators(directory.path())))
    {
        qDebug() << "remove dir" << directory.path() << " faild!";
        error = true;
    }

    return !error;
}

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用QDir类中的removeRecursively()函数来删除一个目录及其所有子目录和文件;使用QFile类中的copy()函数来拷贝一个文件。下面是一个简单的示例代码,实现删除一个目录拷贝一个目录: ```cpp #include <QDir> #include <QFile> // 删除目录及其子目录和文件 bool removeDir(const QString &dirPath) { QDir dir(dirPath); if (!dir.exists()) { return true; } // 遍历目录和子目录 foreach (const QFileInfo &info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) { if (info.isDir()) { // 递归删除目录 if (!removeDir(info.filePath())) { return false; } } else { // 删除文件 if (!dir.remove(info.fileName())) { return false; } } } // 删除目录 return dir.rmdir(dirPath); } // 拷贝目录 bool copyDir(const QString &srcPath, const QString &dstPath) { QDir srcDir(srcPath); QDir dstDir(dstPath); if (!dstDir.exists()) { dstDir.mkpath(dstPath); } // 遍历目录和子目录 foreach (const QFileInfo &info, srcDir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) { QString srcFilePath = info.filePath(); QString dstFilePath = dstPath + "/" + info.fileName(); if (info.isDir()) { // 递归拷贝目录 if (!copyDir(srcFilePath, dstFilePath)) { return false; } } else { // 拷贝文件 if (!QFile::copy(srcFilePath, dstFilePath)) { return false; } } } return true; } int main() { // 删除目录 if (removeDir("/path/to/directory")) { qDebug() << "Directory successfully removed"; } else { qDebug() << "Failed to remove directory"; } // 拷贝目录 if (copyDir("/path/to/source/directory", "/path/to/destination/directory")) { qDebug() << "Directory successfully copied"; } else { qDebug() << "Failed to copy directory"; } return 0; } ``` 其中,/path/to/directory是要删除目录的路径;/path/to/source/directory和/path/to/destination/directory是要拷贝的源目录和目标目录的路径。如果目录删除成功,将输出"Directory successfully removed";如果删除失败,将输出"Failed to remove directory";如果目录拷贝成功,将输出"Directory successfully copied";如果拷贝失败,将输出"Failed to copy directory"。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值