#define _IS_DIR_ 0x4
#define _IS_FILE_ 0x8
void 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);
}
}
}
}
}
LINUX C++ 按修改时间清理过期文件函数实现
最新推荐文章于 2024-08-17 05:29:03 发布