目录
一、获取系统路径
1. C盘目录下的隐藏文件夹
// C:/Users/Administrator/AppData
QDir::homePath() + "/AppData";
QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/AppData";
2. 桌面路径
// C:/Users/Administrator/Desktop
QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)
3. 软件当前工作目录
// testApp/package
// D:/BuildTrees/build-my_qml_test-Debug
QDir::currentPath()
4. 动态库路径
// testApp/package/bin
QCoreApplication::applicationDirPath()
二、复制文件夹
将sourceFolder文件夹内的全部File和Folder, 复制到指定位置destinationFolder
int copyFolder(const QString &sourceFolder, const QString &destinationFolder)
{
QDir sourceDir(sourceFolder);
if (!sourceDir.exists())
{
qWarning() << "Source path does not exist: " << sourceFolder;
return -1;
}
// 遍历文件,进行复制
QStringList files = sourceDir.entryList(QDir::Files);
foreach (const QString &file, files)
{
QString sourceFilePath = sourceFolder + "/" + file;
QString destinationFilePath = destinationFolder + "/" + file;
QFile::copy(sourceFilePath, destinationFilePath);
}
// 遍历文件夹,递归复制内部的文件
QStringList dirs = sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &dir, dirs)
{
QString sourceSubDir = sourceFolder + "/" + dir;
QString destinationSubDir = destinationFolder + "/" + dir;
copyFolder(sourceSubDir, destinationSubDir);
}
return 0;
}
三、删除文件夹
1. 删除指定文件/文件夹
#include <QFile>
#include <QDir>
#include <QString>
bool deleteFileOrFolder(const QString &strPath)//要删除的文件夹或文件的路径
{
if (strPath.isEmpty() || !QDir().exists(strPath))//是否传入了空的路径||路径是否存在
return false;
QFileInfo FileInfo(strPath);
if (FileInfo.isFile())//如果是文件
QFile::remove(strPath);
else if (FileInfo.isDir())//如果是文件夹
{
QDir qDir(strPath);
qDir.removeRecursively();
}
return true;
}
2. 删除文件夹内部分文件
如果folderPath文件夹内的文件数量超出上限uplimit,则删除最老的几个文件,只保留lowlimit个。
int clearFolder(const QString &folderPath, const int &uplimit, const int &lowlimit)
{
QDir folder(folderPath);
if (!folder.exists())
{
qWarning() << "folder path does not exist: " << folderPath;
return -1;
}
// 获取文件夹中所有的文件和文件夹,同时排序
QFileInfoList fileList = folder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
if (fileList.count()<= uplimit) {
qDebug() << "No need to clean the folder.";
return 0;
}
// 删除多余的文件
for (int i = lowlimit; i < fileCount; ++i) {
QString filePath = fileList.at(i).absoluteFilePath();
QDir delFolder(filePath);
delFolder.removeRecursively();
}
return 0;
}