int DeleteFileByDays(char *fileDir,int days,int clearMode)
{
int ret = 0;
int fileTotalNum = 0;
int j = 0,len = 0,i = 0;
char fullFileName[512+1];
char fileName[256+1];
char fileDate[14+1];
char oldDate[14+1];
struct dirent **nameList;
struct stat fileInfo;
struct tm *fileTM;
// 获取前N天的日期
memset(oldDate,0,sizeof(oldDate));
GetDateBeforSpecDays(days,oldDate);
// 打开目录
if ((fileTotalNum = scandir(fileDir,&nameList,0,alphasort)) < 0)
{
printf("in DeleteFileByDays:: scandir [%s] error!\n",fileDir);
//free(nameList);
printf("打开文件目录失败");
return(fileTotalNum);
}
for(j = 0; j < fileTotalNum; j++)
{
len = sprintf(fileName,"%s",nameList[j]->d_name);
if (fileName[0] == '.')
continue;
fileName[len] = 0;
len = sprintf(fullFileName,"%s/%s",fileDir,fileName);
fullFileName[len] = 0;
if (clearMode == 1) // 根据文件名清理
{
len = 0;
for (i = 0; i < strlen(fileName); i++)
{
if (IsDigitChar(fileName[i]))
len += sprintf(fileDate + len,"%c",fileName[i]);
else
len = 0;
if (len == 8)
break;
}
fileDate[len] = 0;
if (!IsValidFullDateStr(fileDate))
continue;
}
else if (clearMode == 2) // 根据文件属性
{
memset(&fileInfo,0,sizeof(fileInfo));
if ((ret = stat(fullFileName,&fileInfo)) < 0)
{
printf("in DeleteFileByDays:: stat [%s] error!\n",fullFileName);
continue;
}
// 获取文件时间
fileTM = localtime(&fileInfo.st_mtime);
memset(fileDate,0,sizeof(fileDate));
strftime(fileDate,sizeof(fileDate),"%Y%m%d",fileTM);
}
// 检查是否需要删除文件
if (strcmp(fileDate,oldDate) <= 0)
{
if ((ret = unlink(fullFileName)) < 0)
{
printf("in DeleteFileByDays:: unlink[%s] error!\n",fullFileName);
continue;
}
else
printf("in DeleteFileByDays:: delete[%s]!\n",fullFileName);
}
}
free(nameList);
return 0;
}
阅读(1071) | 评论(0) | 转发(0) |