C++ 定期清楚日志文件功能

在实际项目中,经常需要定期清理文件(如日志文件、历史数据文件),这里用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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值