#define DELETE_INTERVAL_SECOND (15*24*60*60) // 删除15天之前的日志文件
// 获取日志文件的最后修改时间
// 参数:strFilePath[in], sysTime[out]
__int64 GetFileModifyTime( LPCTSTR strFilePath )
{
SYSTEMTIME sysTime;
HANDLE hFile = INVALID_HANDLE_VALUE;
FILETIME localFileTime;
WIN32_FIND_DATA wfd;
memset( &wfd, 0, sizeof(wfd) );
hFile = FindFirstFile( strFilePath, &wfd );
if ( hFile == INVALID_HANDLE_VALUE )
{
return 0;
}
BOOL bRet = FileTimeToLocalFileTime( &wfd.ftLastWriteTime, &localFileTime );
if ( !bRet )
{
return 0;
}
memset( &sysTime, 0, sizeof(sysTime) );
bRet = FileTimeToSystemTime( &localFileTime, &sysTime );
if ( !bRet )
{
return 0;
}
FindClose( hFile );
tm tmTime = { sysTime.wSecond, sysTime.wMinute, sysTime.wHour, sysTime.wDay,
sysTime.wMonth-1, sysTime.wYear-1900, sysTime.wDayOfWeek, 0, 0 };
return mktime( &tmTime );
}
void DeleteLogFile( LPCTSTR strLogPath )
{
if ( !PathFileExists( strLogPath ) )
{
return;
}
time_t tCurTime = time( NULL ); // 获取当前时间
tstring strFindFileName = strLogPath;
strFindFileName += _T("\\*.*");
WIN32_FIND_DATA wfd;
HANDLE hFindFile = FindFirstFile( strFindFileName.c_str(), &wfd );
if ( hFindFile == INVALID_HANDLE_VALUE )
{
return;
}
while ( true )
{
if ( wfd.cFileName[0] != _T('.') )
{// 非本级或上级目录
if ( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) // 目录
{
if ( !FindNextFile( hFindFile, &wfd ) )
{
break;
}
continue;
}
else if ( wfd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM ) // 系统文件,不处理
{
if ( !FindNextFile( hFindFile, &wfd ) )
{
break;
}
continue;
}
else // 用户日志文件
{
tstring strLogFile = strLogPath;
strLogFile += _T("\\");
strLogFile += wfd.cFileName;
time_t tModifyTime = GetFileModifyTime( strLogFile.c_str() );
// 如果是15天之前的文件,则将之删除掉(拿当前时间和文件的最后修改时间作比较)
if ( tCurTime - tModifyTime > DELETE_INTERVAL_SECOND )
{
DeleteFile( strLogFile.c_str() );
}
}
}
if ( !FindNextFile( hFindFile, &wfd ) )
{
break;
}
};
FindClose( hFindFile );
}
C++定期删除旧的日志文件(日志文件存在指定的目录中)
最新推荐文章于 2023-10-27 14:30:49 发布
这段代码定义了一个常量DELETE_INTERVAL_SECOND,表示15天的时间(以秒计)。它包含两个函数:GetFileModifyTime用于获取日志文件的最后修改时间,DeleteLogFile遍历指定路径下的文件,如果文件是15天之前的,则进行删除操作。
摘要由CSDN通过智能技术生成