**
更新時間:2020-06-19
**
之前通過c++寫了一個保留日誌的文件。
那時候是利用獲取文件夾的創建時間進行前後日期判斷的。
這種就避免了文件夾名字的不同。也可以保留幾天的日誌文件。
現在我用的QT寫的,因爲是日誌,我的日誌文件夾採用日期每天生成一個。以日期命名(偷個懶)
統一放在logs下,裏面有很多個日期文件,日誌文件放在每個日期文件下。
思路:
1.獲取日誌文件裏有幾個文件夾
2.數量超過n個(天)。
3.獲取文件夾名字轉成int型,並進行排序。
4.把當前幾個文件夾-你要保留的日期(n天)再遍歷
5.獲得應該要刪除的文件夾名。然後進行刪除。
建議採用定時器,到一個時間就執行這個函數。
至此就完成了日誌文件的更新保留功能。
所需頭文件:
#include < QDir>
#include < QList>
#include < QDateTime>
下面是代碼:
void Typechange::mkdirdatefile()
{
QDir dir;
if(!dir.exists("logs")){
dir.mkdir("logs");
qDebug()<<"not logs file";
}else{
qDebug()<<"have logs file";
}
QString curdate=getdate();
QDir datedir;
if(!datedir.exists("logs/"+curdate)){
datedir.mkdir("logs/"+curdate);
qDebug()<<"create datelogs file";
}
}
bool Typechange::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;
}
QStringList Typechange::GetDirNameList(const QString &strDirpath)
{
QDir dir(strDirpath);
QFileInfoList Info_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
QListIterator<QFileInfo> Iterator(Info_list);
QStringList strDirNameList;
QFileInfo Info;
while (Iterator.hasNext())
{
Info = Iterator.next();
if (Info.isDir())
{
strDirNameList << QDir(Info.absoluteFilePath()).dirName();
// qDebug()<<QDir(Info.absoluteFilePath()).dirName();
}
}
return strDirNameList;
}
void Typechange::delexpiredfile(const QString &strDirpath)
{
QStringList foldername=GetDirNameList(strDirpath);
if(foldername.size() > 7)
{
QList<int> intfn;
for(int i = 0; i< foldername.size();++i)
{
intfn.append(foldername.at(i).toInt());
}
//小到大排序
qSort(intfn.begin(),intfn.end());
for(int j = 0; j< intfn.size()-7;++j)
{
QString dd=QString::number(intfn.at(j));
qDebug()<<"delete file"<<dd<<DeleteFileOrFolder(strDirpath+"/"+dd);
}
}else
{
qDebug()<<"dairyfile not greater than 7";
}
}
QString Typechange::getdate()
{
QDateTime current_date_time = QDateTime::currentDateTime();
QString date = current_date_time.toString("yyyyMMdd");
// QString date = current_date_time.toString("yyyy-MM-dd hh:mm::ss.zzz");
return date;
}
使用方法:
#include < QCoreApplication>//獲取exe路徑
QString execurrentPath = QCoreApplication::applicationDirPath();
delexpiredfile(execurrentPath +"/(你的日誌文件夾名:我的是logs)");
~持續更新優化