【问题标题】:C++ - Linux - Delete Files In A Specified Directory That Are At Least 5 Days OldC++ - Linux - 删除指定目录中至少 5 天前的文件
【发布时间】:2014-06-26 18:37:39
【问题描述】:

如何修改此代码以删除指定目录中至少 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 天的文件?任何建议将不胜感激!

【问题讨论】:

    标签: c++ linux


    【解决方案1】:

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

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

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

    我还建议收集要删除的文件名列表,例如在std::vector&lt;std::string&gt;

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

    (您可能不想在家庭作业中使用system

    【讨论】:

      【解决方案2】:

      可以这么简单:

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

      但如果您有特定要求,则需要发布它们。

      【讨论】:

      • 我不确定这是否是此类作业的有效答案。
      • @BasileStarynkevitch 为什么我要对要求进行免责声明?
      • @asveikau OP 的问题 - Linux 上的 C++。
      • @Slava - 他们在 Linux 上使用 C++ 的事实并没有让system() 成为一个坏主意。
      猜你喜欢
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2019-07-11
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多