以下代码主要有以下功能:
- 判断文件夹是否存在
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 }