c++ - Linux -删除指定目录下超过5天的文件

C++ - Linux - Delete Files In A Specified Directory That Are At Least 5 Days Old

本文关键字:5天 文件 删除 Linux c++      更新时间:2023-10-16

如何修改此代码以删除指定目录中至少7天前的所有文件?以下是我的源代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <direct.h>
#include <cstring>
int main(int argc, char* argv[1]) { 
 if (argc < 2) { 
      std:cerr<<"Usage: " << argv[0] << " <filename>" << std::endl;
      return 1;
 }
 struct stat buffer;
 for (int i; i < argc; ++i) { 
      int result = stat(argc[i], &buffer);
      if (result != 0) { 
           std::cerr << argv[i] << ": "<<stderror(errno) << std::endl;
           continue;
      }
      char datetime[100] = [0];
      const struct tm* time = localtime(sbuffer.st_mtime);
      result = strftime(datetime, 100, "%c", time);
      std::cout << argv[i] << ": " << datetime << std::endl;
 }
 return 0;
}

我如何得到这个文件的年龄,并删除超过7天的文件?任何建议将不胜感激!

仔细阅读 stat(2)和time(7)手册页。您的sbuffer包含st_mtime字段。将其与当前时间进行比较,例如使用time(2)

请注意,一天通常是86400秒,所以7天是7*86400,即604800秒。

删除文件,使用unlink(2)。我建议使用readdir(3)和opendir(3)来读取目录。(但忽略...条目)。

我还建议收集要删除的文件名列表,例如在std::vector<std::string>

如果要递归扫描目录(及其子目录等),请考虑nftw(3)

(你可能不想在你的家庭作业中使用system)

可以这么简单:

system( "find <dir> -maxdepth 1 -mtime 5 -exec rm -f {} ;" );