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():分别用于删除文件和空文件夹。

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

相关推荐
andyweike29 分钟前
php笔记
开发语言·笔记·php
Circ.1 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~3 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411363 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅4 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿5 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
hiahiahia1235 小时前
实现完整 Tool Dispatcher
开发语言·前端
AC赳赳老秦6 小时前
公开音频转写信息提取:OpenClaw 处理发布会与听证会文本并提取核心决策信息
大数据·开发语言·汇编·数据库·人工智能·deepseek·openclaw