您的位置:首页 > 其它

定期删除旧的日志文件(日志文件存在指定的目录中)

2014-04-28 23:18 996 查看
#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 );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: