How to delete a directory and its subfiles in Qt?
In Qt, you can delete a directory and its subdirectories using the removeRecursively method of the QDir class. Here is an example code snippet:
#include <QDir>
#include <QDebug>
void removeDirectory(const QString& path)
{
QDir dir(path);
if (dir.exists()) {
// 获取目录下所有文件和子目录
QStringList fileList = dir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot);
// 遍历子文件和子目录
foreach(const QString& fileName, fileList) {
QString filePath = dir.filePath(fileName);
QFileInfo fileInfo(filePath);
// 如果是文件则直接删除
if (fileInfo.isFile()) {
QFile::remove(filePath);
}
// 如果是目录则递归调用removeDirectory删除子目录
else if (fileInfo.isDir()) {
removeDirectory(filePath);
}
}
// 删除目录
dir.rmdir(path);
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString path = "your_directory_path";
removeDirectory(path);
return a.exec();
}
In the above example code, the removeDirectory function uses a recursive method to delete a directory and its subfiles. It first checks if the directory exists, if so, it retrieves all the files and subdirectories within the directory. It then iterates through the subfiles and subdirectories, deleting files directly and recursively calling the removeDirectory function to delete subdirectories. Finally, it deletes the directory itself.