想用QT編一段刪除文件夾或文件的代碼,網上搜索了很多,關於刪除文件夾都用遞歸刪除的方法,因為非空文件夾不能直接刪除,只能先清空文件夾里的東西,才能執行刪除文件夾的操作。實際上QT5之后有更簡便的方法,就是用QDir::removeRecursively(),詳細的可以查QT幫助文檔。
利用QDir::removeRecursively()和QFile::remove(),可以寫出很簡單的刪除文件夾或文件的操作。#include <QFile>
#include <QDir>
#include <QString>
1 bool DeleteFileOrFolder(const QString &strPath)//要刪除的文件夾或文件的路徑
2 { 3 if (strPath.isEmpty() || !QDir().exists(strPath))//是否傳入了空的路徑||路徑是否存在
4 return false; 5
6 QFileInfo FileInfo(strPath); 7
8 if (FileInfo.isFile())//如果是文件
9 QFile::remove(strPath); 10 else if (FileInfo.isDir())//如果是文件夾
11 { 12 QDir qDir(strPath); 13 qDir.removeRecursively(); 14 } 15 return true; 16 }