【问题标题】:How to Find number and folder of files in a directory如何在目录中查找文件的数量和文件夹
【发布时间】:2020-06-17 18:43:36
【问题描述】:

我需要在一个目录中查找文件和文件夹的数量。在此之前我使用的是 MinGW 编译器,我尝试使用 d_type 但我无法编译我的代码。

而且我不在乎“。”和“..”目录。我不想计算它们。

所以我写了一个这样的程序。这个程序可以很容易地找到一个目录中有多少个文件和文件夹。

但是当我给一个新名称一个文件夹而不是新文件夹时,新文件夹(1)。该程序将该文件夹计算为一个文件。

我能做什么?我真的卡住了。我要找出多少个文件和多少个文件夹...

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

int
main(int argc, char *argv[])
 {

int file_count = 0;
int dir_count = 0;
struct dirent * entry;
struct stat filestat;
size_t nfiles = 0, ndirs = 0;
DIR *dp;

if (argc != 2)
{
    printf("usage: put directory_name\n");
    exit(-1);
}


if ((dp = opendir(argv[1])) == NULL)
{
    printf("Error: can't open %s\n", argv[1]);
    exit(-2);
}

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

    if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
        continue;
    }

     stat(entry->d_name,&filestat);

    if( S_ISDIR(filestat.st_mode) ){
      ndirs++;
      }
    else
       nfiles++;
}

closedir(dp);

  printf("%lu Files, %lu Directories\n", nfiles, ndirs);

return(0);
 }

【问题讨论】:

  • 正如我之前所说,我不能使用 d_type 和 DT_REG。我无法在 Windows 上编译该代码。
  • 好吧,你没有明确说出来。但我已删除链接并关闭投票。

标签: c io system-calls stat readdir


【解决方案1】:

entry-&gt;d_name 将只包含文件名,而不是完整路径,因此如果调用 stat() 它将失败,除非该文件恰好存在于当前目录中。

另请注意,您的代码不是递归的,因此它不会计算子文件夹中的内容。

【讨论】:

  • 我该如何解决?我真的被困住了。我什么都做不了。我必须在 Windows 上制作这个程序。我什至不能使用 entry->d_type。
  • 这有助于描述部分问题,但在回答问题时不会走得太远。我不是拒绝投票,但这是可能会吸引一些人的答案类型:) 建议将其放在 cmets 中,除非您打算再充实一点。
  • 我能理解。我是这里的编程初学者,也是新手。所以我两者都不擅长:)我只需要帮助......
猜你喜欢
  • 2020-10-07
  • 2012-11-12
  • 2013-03-19
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 2014-08-13
相关资源
最近更新 更多