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

#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 );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值