1. 程式人生 > 其它 >Qt 建立資料夾、判斷資料夾是否存在、資料夾是否為空、清空資料夾

Qt 建立資料夾、判斷資料夾是否存在、資料夾是否為空、清空資料夾

以下程式碼主要有以下功能:

  • 判斷資料夾是否存在dir.exists()
  • 判斷資料夾是否為空dir.entryInfoList()
  • 清空資料夾dir.removeRecursively()
  • 生成新資料夾 dir.mkpath()
 1 // @brief 初始化路徑(若存在且有檔案,則確認是否清空)
 2 // return true 成功 false 失敗
 3 bool MainWindow::initReportPath()
 4 {
 5     QString pathName = QStringLiteral("專案一路徑");
 6     // 建立資料夾(若不存在則建立,若存在詢問使用者是否清空)
7 QString reportPath = QCoreApplication::applicationDirPath() + "/DataReport/" + pathName + "/"; 8 9 QDir dir; 10 bool res; 11 if (!dir.exists(reportPath)) 12 { 13 res = dir.mkpath(reportPath); 14 } 15 else 16 { 17 // 已存在,判斷資料夾是否為空,如果不是則提示使用者是否清空 18
dir.setPath(reportPath); 19 dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); 20 QFileInfoList list = dir.entryInfoList(); 21 22 if (list.count() <= 0) 23 { 24 qDebug() << "資料夾為空"; 25 res = true; 26 } 27 else
28 { 29 qDebug() << "資料夾不為空"; 30 QMessageBox::StandardButton reply; 31 reply = QMessageBox::question(this, "提示", "目錄已經存在,是否清空資料夾", QMessageBox::Yes | QMessageBox::No); 32 33 if (reply == QMessageBox::Yes) 34 { 35 dir.setPath(reportPath); 36 dir.removeRecursively(); 37 res = dir.mkpath(reportPath); 38 } 39 else 40 { 41 QMessageBox::information(NULL, "提示", "請重新設定報告儲存路徑"); 42 res = false; 43 } 44 } 45 } 46 47 if (res) 48 { 49 QMessageBox::information(this, "提示", "本次報告路徑設定完成"); 50 // 設定全域性路徑名稱 51 reportPathStr = reportPath; 52 } 53 54 return res; 55 }