qt c++删除文件夹下旧的文件或文件夹

根据读取到的指定文件夹路径进行对文件夹按照时间排序删除比较旧的文件夹,并按照设定的最大文件夹数量执行删除操作

#ifndef FILE_MANAGER_H
#define FILE_MANAGER_H

#include <QObject>
#include <QList>
#include <QFileInfo>

#include "common_ext_global.h"

/*
* 文件夹处理,指定路径下的旧的文件夹删除操作
*/

class COMMON_EXT_EXPORT FileManager : public QObject
{
	Q_OBJECT
public:
	static bool deleteFileOrFolder(const QString& strPath);
	static QList<QFileInfo> getDirNameList(const QString& strDirpath);
	/*
	* 删除旧的文件夹 
	* @文件夹路径
	* @保留最大旧的文件数量
	*/
	static void removeOldFolders(const QString& strDirpath, int num_old_file_save = 3);
};


#endif


#include "filemanager.h"

#include <QDir>
#include <QList>
#include <QDateTime>
#include <QDirIterator>


bool FileManager::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;
}

QList<QFileInfo> FileManager::getDirNameList(const QString& strDirpath)
{
	QDir dir(strDirpath);
	QFileInfoList Info_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
	QListIterator<QFileInfo> Iterator(Info_list);
	QList<QFileInfo> strDirNameList;
	QFileInfo Info;
	while (Iterator.hasNext())
	{
		Info = Iterator.next();
		if (Info.isDir())
		{
			strDirNameList << Info;
			//            qDebug()<<QDir(Info.absoluteFilePath()).dirName();
		}
	}
	return strDirNameList;
}

void FileManager::removeOldFolders(const QString& strDirpath, int num_old_file_save)
{
	QList<QFileInfo> foldername = getDirNameList(strDirpath);
	if (foldername.size() > num_old_file_save)
	{
		QList<QDateTime> fileTime;
		for (int i = 0; i < foldername.size(); i++) {
			fileTime.append(foldername.at(i).lastModified());
		}

		qSort(fileTime.begin(), fileTime.end());

		
		for (int i = 0; i < (fileTime.size() - num_old_file_save); i++)
		{
			for (int j = 0; j < fileTime.size(); j++)
			{
				if (foldername.at(j).lastModified() == fileTime.at(i))
					deleteFileOrFolder(foldername.at(j).absoluteFilePath());
			}
		}
	}
}

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值