QT 删除指定文件夹中的所有文件
时间: 2023-08-02 12:09:04 浏览: 507
可以使用 QDir 类遍历指定文件夹中的所有文件,并使用 QFile 类删除文件。具体代码如下:
```cpp
void deleteAllFilesInDir(const QString& dirPath)
{
QDir dir(dirPath);
// 遍历目录中的所有文件
QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
foreach (QFileInfo fileInfo, fileList)
{
QFile file(fileInfo.filePath());
if (file.exists())
{
// 删除文件
if (!file.remove())
{
qDebug() << "Failed to remove file: " << fileInfo.filePath();
}
}
}
// 遍历目录中的所有子目录
QStringList dirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QString subDir, dirList)
{
QString subDirPath = dirPath + QDir::separator() + subDir;
// 递归删除子目录中的所有文件
deleteAllFilesInDir(subDirPath);
}
}
```
你可以调用这个函数并传入需要删除的文件夹路径,函数会递归删除该目录下的所有文件和子目录中的所有文件。例如:
```cpp
deleteAllFilesInDir("D:/test");
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)