Qt清空文件夹下的内容

Qt清空文件夹下的内容

你可以使用 QDir 类来清空文件夹下的所有内容。以下是一个示例,展示了如何删除指定文件夹中的所有文件和子文件夹:

cpp 复制代码
#include <QCoreApplication>
#include <QDir>
#include <QFileInfoList>
#include <QDebug>

bool clearDirectory(const QString &dirPath) {
    QDir dir(dirPath);
    if (!dir.exists()) {
        qDebug() << "Directory does not exist:" << dirPath;
        return false;
    }

    // 获取文件夹内所有文件和子文件夹
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历并删除文件和子文件夹
    foreach (const QFileInfo &fileInfo, fileList) {
        if (fileInfo.isDir()) {
            // 如果是文件夹,递归清空
            clearDirectory(fileInfo.absoluteFilePath());
            dir.rmdir(fileInfo.absoluteFilePath());
        } else {
            // 如果是文件,直接删除
            dir.remove(fileInfo.absoluteFilePath());
        }
    }

    return true;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString folderPath = "path/to/your/folder";  // 替换为目标文件夹路径
    if (clearDirectory(folderPath)) {
        qDebug() << "Directory cleared successfully!";
    } else {
        qDebug() << "Failed to clear the directory.";
    }

    return a.exec();
}

代码解释:

  1. QDir:用于操作目录。
  2. entryInfoList():获取文件夹中的所有条目(包括文件和子目录)。
  3. 递归删除 :如果目录中包含子文件夹,首先递归调用 clearDirectory 删除子文件夹的内容,然后删除该子文件夹。如果是文件,直接删除。
  4. remove()rmdir():分别用于删除文件和空文件夹。

这段代码将清空指定目录及其所有子目录中的内容。

相关推荐
biter down5 小时前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
郝学胜-神的一滴5 小时前
Qt 高级开发 009: C++ Lambda 表达式
开发语言·c++·qt·软件构建
星栈独行5 小时前
我在 Rust 全栈项目里用 JWT 做无状态认证
开发语言·后端·rust·前端框架·开源·github·web
石山代码6 小时前
C++ 轻量级日志系统
开发语言·c++
小技与小术6 小时前
玩转Flask
开发语言·python·flask
SilentSamsara6 小时前
Python 性能优化:tracemalloc、profiling 与 C 扩展加速
开发语言·python·青少年编程·性能优化
冰小忆6 小时前
大驼峰命名规范和小驼峰命名规范的区别是什么?
开发语言·python
এ慕ོ冬℘゜8 小时前
JS 前端基础面试题
开发语言·前端·javascript
浩少7028 小时前
【无标题】
java·开发语言
nnsix9 小时前
C# 字符串 根据换行符分割
开发语言·c#