【qt】每日删除文件
2026/6/23 14:35:15 网站建设 项目流程
QSet<QDate>cleanupDates;// 记录已执行清理的日期voidsaveLog(constQString&logMsg){QDateTime currentDateTime=QDateTime::currentDateTime();QString dateString=currentDateTime.toString("yyyy-MM-dd hh:mm:ss:zzz");// 按日期分文件存储,方便管理QString datePrefix=currentDateTime.toString("yyyyMMdd");QString logFileName=QString(u8"%1/光管日志%2_%3.txt").arg(QCoreApplication::applicationDirPath()).arg(m_XrayComPort).arg(datePrefix);// 检查今天是否已执行清理QDate today=QDate::currentDate();if(!cleanupDates.contains(today)){cleanupOldLogFiles(3);// 清理3天前的日志文件cleanupDates.insert(today);// 清理过期的清理记录(保留最近30天的记录)QDate cutoff=today.addDays(-30);QSet<QDate>newSet;for(constQDate&date:cleanupDates){if(date>=cutoff){newSet.insert(date);}}cleanupDates=newSet;}QFilefile(logFileName);if(file.open(QIODevice::Append|QIODevice::Text)){QTextStreamout(&file);out.setCodec("UTF-8");QString XrayMsg=QString("%1 %2\n").arg(dateString).arg(logMsg);out<<XrayMsg;file.close();}}// 按日期文件清理voidcleanupOldLogFiles(intkeepDays){QString logDir=QCoreApplication::applicationDirPath();QDirdirectory(logDir);// 查找所有光管日志文件QString filter=QString("光管日志%1_*.txt").arg(m_XrayComPort);QStringList logFiles=directory.entryList(QStringList()<<filter,QDir::Files);QDateTime cutoffDate=QDateTime::currentDateTime().addDays(-keepDays);for(constQString&fileName:logFiles){QString filePath=directory.filePath(fileName);QFileInfofileInfo(filePath);// 根据最后修改时间删除if(fileInfo.lastModified()<cutoffDate){QFile::remove(filePath);}}}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询