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 = 10;
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删除指定路径的文件
该文章转载自网络大本营:http://www.xrss.cn/Dev/C/200783016225.Html