LINUX C++ 按修改时间清理过期文件函数实现

来源:互联网 发布:网络防御技术 编辑:程序博客网 时间:2024/06/05 09:47
#define _IS_DIR_ 0x4#define _IS_FILE_ 0x8void DeleteFolder(const char* dir, int nSpanTime){if (dir == nullptr || strlen(dir) <= 0)return;struct stat s;lstat(dir, &s);if ( !S_ISDIR(s.st_mode) ){WriteRunLog(VIS_LOG_ERROR, "%s is not a valid directory.", dir);return;}DIR* pDir = opendir(dir);if (nullptr == pDir){WriteRunLog(VIS_LOG_ERROR, "cannot open dir %s.", dir);return;}struct dirent* filename;while ( (filename = readdir(pDir)) != nullptr ){if (strcmp(filename->d_name, ".") == 0 || 0 == strcmp(filename->d_name, ".."))continue;char szChild[256] = { 0 };sprintf(szChild, "%s/%s", dir, filename->d_name);if (filename->d_type == _IS_DIR_){DeleteFolder(szChild, nSpanTime);}else{lstat(szChild, &s);if (time(nullptr) - s.st_mtim.tv_sec > nSpanTime){if (0 == remove(szChild)){WriteRunLog(VIS_LOG_ERROR, "delete file %s success.", szChild);}else{WriteRunLog(VIS_LOG_ERROR, "delete file %s failed.", szChild);}}}}}

原创粉丝点击