在实际项目中,经常需要定期清理文件(如日志文件、历史数据文件),这里用boost和C++11,完成一个定期清理日志的功能。后续工程中,可将文件路径、清除周期和文件类型等信息做成配置文件方式,灵活运用在需要的地方。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<chrono>
#include<io.h>
#include<vector>
#include<windows.h>
#include<boost/filesystem.hpp>
#include<thread>
using namespace boost::filesystem;
using namespace std;
/*
功能:定时删除指定日期前的日志文件
@ path 文件路径 如:"E:/Agent/bin/log/"
@ fileType 文件类型 如:"*.log"
@ day 天数
*/
void FileThread1(string path, string fileType,int day)
{
while (1)
{
_finddata_t fileinfo;
long handle;
if ((handle = _findfirst((path + fileType).c_str(), &fileinfo)) == -1)
{
Sleep(1000);
continue;
}
string fileName = path + string(fileinfo.name);
try{
time_t fileTime = last_write_time(fileName); //文件的最后修改时间
chrono::system_clock::time_point current = chrono::system_clock::now(); //当前时间
time_t nowTime = chrono::system_clock::to_time_t(current); //转为time类型的当前时间
time_t timeInterval = 24 * 60 * 60 * day;//秒 天
time_t Interval = nowTime - fileTime;
if (Interval>timeInterval)
{
cout << day<<"天前文件:" << fileName << endl;
bool ret = remove(fileName); //删除文件
if (ret)
{
cout << "文件删除成功" << endl;
}
else
{
cout << "文件删除失败" << endl;
}
}
else
{
//cout << day << "天内文件:" << fileName << endl;
}
}
catch (filesystem_error e)
{
//std::cout << "文件异常!" << std::endl; milliseconds()毫秒
}
this_thread::sleep_for(chrono::seconds(5)); //秒
}
}
int main()
{
string path = "E:/project/Process/bin/log/";
string fileType = "*.log";
int day = 3;
thread t1(FileThread1, path, fileType,day);
if (t1.joinable())
{
t1.join();
}
system("pause");
return 0;
}