删除过期和过大文件 DeleteFile

1.源程序 

 // Delete file one month ago or bigger than 50M
 char  strPath[128];
 char  strCurDir[128];
 CString  strLog;
 CFileFind cf;
 BOOL  bFindFlag = TRUE;
 time_t  tCurTime,tFileTime,tElapsedTime;
 CString  strFileName;// log file name
 struct _stat st;// log file info

 memset(strPath,0,sizeof(strPath));
 memset(strCurDir,0,sizeof(strCurDir));

 // get current directory
 if(_getcwd(strCurDir,128) == NULL)
 {
  AfxMessageBox("get current working directory error!");
  return;
 }

 strLog.Format("%s//%s",strCurDir,"//*.log");

 // find the log file
 bFindFlag = cf.FindFile(strLog);
 if(!bFindFlag)
 {
  AfxMessageBox("can not find log file");
  return;
 }

 // get the 1 month ago time_t
 time(&tCurTime);// get system time
 tElapsedTime = 30*24*60*60;
 tCurTime -= tElapsedTime;

 while(bFindFlag)
 {
  bFindFlag = cf.FindNextFile();
  
  if(cf.IsDots() || cf.IsDirectory())
  {
   continue;
  }

  strFileName = cf.GetFilePath();// get file path include file name
  if(_stat((char *)(LPCTSTR)strFileName,&st) < 0)
  {
   continue;
  }

  // file time is one month ago
  tFileTime = st.st_mtime;
  if(tFileTime < tCurTime)
  {
   DeleteFile(strFileName);
  }

  // file size is bigger than 50 M
  if(st.st_size > 50*1024*1024)
  {
   DeleteFile(strFileName);
  }
 }

2.函数说明

1) _getcwd (from msdn lib)

char *_getcwd( char *buffer, int maxlen );

Function:Get the current working directory.

Required Header:<direct.h>

Return Value:返回指向buffer的指针。错误时返回NULL

Parameters:

buffer:保存当前路径

maxlen:保存路径的最大字节数

2)  _stat   (from msdn lib)

int _stat( const char *path, struct _stat *buffer );

Function:Get status information on a file.

Required Header:<sys/stat.h>

Return Value:成功返回0;错误返回-1,表示没有找到相应文件

Parameters

path:要查找文件的实际路径

buffer:保存获得的文件信息

struct _stat 的具体参数见msdn,常用参数有st_mtime(文件的最后修改时间),st_size(文件的字节数)

3) CFileFind 文件查找

4) DeleteFile删除指定路径的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值