Qt 刪除目錄


刪除目標的目錄,若該目錄下有子目錄,一並刪除。

 1 //判斷是否存在子目錄
 2 bool judgeDir(QDir dir)
 3 {
 4     dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
 5     foreach(QFileInfo fileInfo, dir.entryInfoList())
 6     {
 7         if(fileInfo.isDir())
 8         {
 9             return true;
10         }
11         else if(fileInfo.isFile())
12         {
13             return true;
14         }
15         else
16         {
17             return false;
18         }
19     }
20     return true;
21 }
22 
23 //刪除目標目錄
24 void delDir(QString path)
25 {
26     if(path.isEmpty())
27     {
28         QMessageBox::warning(this,tr("警告"),tr("路徑為空"),QMessageBox::Yes);
29         return;
30     }
31     QDir dir(path);
32 
33     dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
34     foreach(QFileInfo fileInfo, dir.entryInfoList())
35     {
36         if(fileInfo.isFile())
37         {
38             if(!fileInfo.isWritable())
39             {
40                 QFile file(fileInfo.absoluteFilePath());
41                 file.setPermissions(QFile::WriteOwner);
42             }
43 
44             fileInfo.dir().remove(fileInfo.fileName());
45 
46         }
47         else if(fileInfo.isDir())
48         {
49             delDir(fileInfo.absoluteFilePath());
50         }
51     }
52     dir.rmpath(dir.absolutePath());
53 }
54 
55 //刪除傳入的目錄
56 void deleteFile(QString path)
57 {
58     QDir dir(path);
59     int saveDel = QMessageBox::question(this,tr("提示"),tr("確定刪除目錄").arg(path), QMessageBox::Yes | QMessageBox::No );
60    
61     if(QMessageBox::Yes == saveDel)
62     {
63         QDir currentDir(path);
64         if(judgeDir(currentDir))
65         {
66             delDir(currentDir.absolutePath());
67         }
68         else
69         {
70             dir.rmdir(path);
71         }
72     }
73 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM