#include#include #include #include #include #include #include #include #include using namespace std; const long day = 86400; //获取文件的给更新时间 long get_file_modify_time(string filepath) { struct stat filehand; FILE *fp; fp = fopen(filepath.c_str(), "r"); int fileid = fileno(fp); fstat(fileid, &filehand); fclose(fp); return filehand.st_mtime; } //获取文件夹中的所有文件 void get_files(const string dirname, vector &filelist) { if(dirname.empty()) return; struct stat s; stat(dirname.c_str(), &s); if(!S_ISDIR(s.st_mode)) return; DIR *dirhand = opendir(dirname.c_str()); if(NULL == dirhand){ exit(EXIT_FAILURE); } dirent *fp = nullptr; while((fp = readdir(dirhand)) != nullptr){ if(fp->d_name[0] != '.'){//十分重要的一行(?) string filename = dirname + "/" + string(fp->d_name); struct stat filemod; stat(filename.c_str(), &filemod); if(S_ISDIR(filemod.st_mode)){ get_files(filename, filelist); } else if(S_ISREG(filemod.st_mode)){ filelist.push_back(filename); } } } closedir(dirhand); return; } bool delete_file(string filepath) { return remove(filepath.c_str()); } bool date_from_now(long now, long modify) { int dis = int((1.0 * (now - modify) / day + 0.5)); return dis >= 9;//删除最近更新时间距今超过14天的文件 } int main() { time_t now; time(&now);//获取当前系统时间 string dir = "/file/cpp";//需要处理的文件夹 vector filelist; get_files(dir, filelist);//获取文件夹中的所有文件 for(auto i : filelist){ if(date_from_now(now, get_file_modify_time(i))){ cout << i << endl; if(!delete_file(i)){ cout << "The file named : " << i << " has been deleted." << endl; } else{ cout << "Delete Failed!" << endl; } } } return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)