C++遍历目录,并把目录里超过7天的文件删除,适用于项目里删除过期的日志,或者视频文件。
在windows和linux下测试通过。
windows测试结果:
linux测试结果:
源码:
1 #include <time.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include "dirent.h" 6 #include <sys/stat.h> 7 #include <errno.h> 8 #ifdef WIN32 9 10 #else 11 #include <unistd.h> 12 #endif 13 14 static int find_directory (const char *dirname); 15 16 17 int main(int argc, char *argv[]) 18 { 19 int i; 20 int result; 21 22 //循环遍历命令行里的每个目录 23 i = 1; 24 while (i < argc) { 25 result = find_directory (argv[i]); 26 if (result == -1) { 27 exit (EXIT_FAILURE); 28 } 29 i++; 30 } 31 32 //如果命令行参数为空,则遍历当前工作目录 33 if (argc == 1) { 34 find_directory ("."); 35 } 36 return EXIT_SUCCESS; 37 } 38 39 //删除7天前的文件 40 int RemoveFile( char* filename ) 41 { 42 int result; 43 //errno_t errno; 44 //获取文件信息 45 #ifdef WIN32 46 struct _stat buf; 47 result = _stat(filename, &buf); 48 #else 49 struct stat buf; 50 result = stat(filename, &buf); 51 #endif 52 53 if( result != 0 ) 54 { 55 perror( "Problem getting information" ); 56 switch (errno) 57 { 58 case ENOENT: 59 printf("File %s not found. ", filename); 60 break; 61 case EINVAL: 62 printf("Invalid parameter to _stat. "); 63 break; 64 default: 65 /* Should never be reached. */ 66 printf("Unexpected error in _stat. "); 67 } 68 return -1; 69 } 70 else 71 { 72 // Output some of the statistics: 73 printf( "File size : %ld ", buf.st_size ); 74 printf( "Drive : %c: ", buf.st_dev + 'A' ); 75 76 time_t t; 77 tzset(); /*tzset()*/ 78 t = time(NULL); 79 if((t - buf.st_mtime) > 604800)//604800是7天的秒数,下面是删除超过7天的文件 80 { 81 remove(filename); 82 printf("remove file : %s " ,filename); 83 } 84 return 0; 85 } 86 87 } 88 89 //遍历子目录和目录中的文件 90 static int find_directory(const char *dirname) 91 { 92 DIR *dir; 93 char buffer[PATH_MAX + 2]; 94 char *p = buffer; 95 const char *src; 96 char *end = &buffer[PATH_MAX]; 97 int result; //返回结果 98 99 //copy目录名到buffer 100 src = dirname; 101 while (p < end && *src != '