常见的文件夹操作(附源码)
以下是一些常见的文件夹操作:清空文件夹、获取文件夹最新文件、获取文件夹第二新文件、拷贝文件夹
1、清空文件夹
/*删除文件*/
void clearFolder(const QString &folderPath)
{QDir dir(folderPath);// 检查文件夹是否存在if (!dir.exists()) {qWarning() << "Folder does not exist:" << folderPath;return;}/*筛选清空的文件类别*/QStringList list;list << "*.png";dir.setNameFilters(list);// 遍历文件夹中的所有文件和子文件夹QFileInfoList fileList = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs);for (const QFileInfo &fileInfo : fileList) {if (fileInfo.isDir()) {// 递归删除子文件夹clearFolder(fileInfo.absoluteFilePath());dir.rmdir(fileInfo.fileName());}else {// 删除文件QFile::remove(fileInfo.absoluteFilePath());}}
}
2、获取文件夹最新文件
/*获取文件夹中最新的文件*/
QString getNewestFile(const QString &folderPath)
{QDir dir(folderPath);// 检查文件夹是否存在if (!dir.exists()) {qWarning() << "Folder does not exist:" << folderPath;return QString();}// 获取文件夹中的所有文件QFileInfoList fileList = dir.entryInfoList(QDir::Files);/*筛选查找的文件类别*/QStringList list;list << "*.png";dir.setNameFilters(list);if (fileList.isEmpty()) {qWarning() << "No files found in folder:" << folderPath;return QString();}// 初始化最新文件和时间QFileInfo newestFile = fileList.first();QDateTime newestTime = newestFile.lastModified();// 遍历文件列表,找到最新的文件for (const QFileInfo &fileInfo : fileList) {QDateTime fileTime = fileInfo.lastModified();if (fileTime > newestTime) {newestTime = fileTime;newestFile = fileInfo;}}// 返回最新文件的绝对路径return newestFile.absoluteFilePath();
}
3、获取文件夹第二新文件
/*获取文件夹中最二新的文件*/
QString getSecondNewestFile(const QString &folderPath)
{QDir dir(folderPath);if (!dir.exists()) {qWarning() << "Folder does not exist:" << folderPath;return QString();}/*筛选查找的文件类型*/QStringList list;list << "*.png";dir.setNameFilters(list);// 获取文件夹下所有文件QFileInfoList fileList = dir.entryInfoList(QDir::Files, QDir::Time | QDir::Reversed);// 确保至少有2个文件if (fileList.size() < 2) {qWarning() << "There are less than 2 files in the folder.";return QString();}// 倒数第二个文件QFileInfo secondNewestFile = fileList.at(fileList.size() - 2);return secondNewestFile.absoluteFilePath();
}
4、拷贝文件夹
//拷贝文件:
void copyFile(const QString &sourcePath, const QString &destinationDir)
{QFile sourceFile(sourcePath);QString destinationPath = QDir(destinationDir).absoluteFilePath(QFileInfo(sourceFile).fileName());if (sourceFile.exists()) {if (!QFile::copy(sourcePath, destinationPath)) {qDebug() << "文件复制失败: " << sourcePath << " 到 " << destinationPath;}else {qDebug() << "文件复制成功: " << sourcePath << " 到 " << destinationPath;}}else {qDebug() << "源文件不存在: " << sourcePath;}
}
注:如果本文章对您有所帮助,请点赞收藏支持一下,谢谢。^_^
版权声明:本文为博主原创文章,转载请附上博文链接。