【问题标题】:Count number of txt files in a folder and oldest file if number of files greater than 10?如果文件数大于 10,则计算文件夹中的 txt 文件数和最旧的文件数?
【发布时间】:2014-08-17 03:01:50
【问题描述】:

我正在使用以下程序来获取文件夹中的文件数。
如果文件数大于 10,我想从文件夹中删除最旧的文件。

#include<dirent.h>

int file_count = 0

DIR * dirp;

struct dirent * entry;

dirp = opendir("path");

while ((entry = readdir(dirp)) != NULL) {

    if (entry->d_name!=NULL) {

    file_count++;

   }

}


closedir(dirp);

printf("%d", file_count-2);

return 0;
}

【问题讨论】:

    标签: c file-io directory


    【解决方案1】:

    我可以告诉你如何做到这一点。写完代码后回答你自己的问题。

    1. 使用 Scandir() 函数计算目录中的文件数。

      see this

    2. write system(cd /path/to/your/dir/ &amp;&amp; ls -t &gt; res.txt) 它将使用上次修改时间对所有文件进行排序。您也可以按创建日期排序

      see this.

    3. 然后从跳过开始11个文件的文件中一一读取文件名,一个就是你的res.txt,存入string name="filename"

    4. 声明一个类似string cmd="rm -f "的字符串

    5. 使用将文件名附加到strcat(cmd,name);

    6. system(cmd);

    从文件读取到第 4 步,它应该在一个 while 循环中,条件应该是 while( !EOF)

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 2017-12-25
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多