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

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

相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00613 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术13 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript