递归统计目录中的所有文件(包括子目录中的文件)

标签 c linux

我正在做一个计算目录中文件数量的函数(包括子目录和该子目录中的文件)。例如:

基础/目录 1/目录 1.1

目录 1 有:hi.txt、hi2.txt

目录 1.1 有:hi3.txt、hi4.txt、hi5.txt

因此 Base 中文件数的输出应该是 7(忽略 . 和 ..)

目录 1 中文件数的输出应为 6

目录 2 中文件数的输出应该是 3

这是我尝试过的。

void recorrido(const char *actual, int indent, int op, char * output,int numF)
{
    DIR *dir;
    struct dirent *entrada;


    char path[PATH_MAX+1];
    char path2[PATH_MAX+1];

    if (!(dir = opendir(actual))){
        return;
    }


    while ((entrada = readdir(dir)) != NULL)
    {

        if (entrada->d_type == DT_DIR) //Directory
        {
            if ((strcmp(entrada->d_name, ".") != 0) && (strcmp(entrada->d_name, "..") != 0)) //Ignore . and ..
            {

                strcpy(path, actual);
                strcat(path, "/");
                strcat(path, entrada->d_name);


                recorrido(path, indent + 2,op,output,numF++);
                printf("Number of files for %s is %d", path, numF);
            }
        }
    }

 else if (entrada->d_type != DT_DIR){ //just file

            if (strcmp(actual, "") == 0){
                strcpy(path2, "./"); 
                strcat(path2, entrada->d_name);
                strcpy(actual, path2);
            }
            else
            {
                strcpy(path2, actual);
                strcat(path2, "/");
                strcat(path2, entrada->d_name);
                //printf("File path is %s\n",path2);
                numF++;
            }
        }


    closedir(dir);

}

我在为每个目录打印正确数量的文件时遇到问题,如果我在 base 中有 2 个文件夹(test 1 和 test 2),它将考虑这些文件夹,但如果我在 test 1 中有一些东西,它将忽略它.

最佳答案

如评论中所述,您需要返回增加的值。

  1. 更改函数签名:

    int recorrido(const char *actual, int indent, int op, char *output, int numF)
    
  2. 改变函数调用自身的方式:

    numF = recorrido(path, indent + 2, op, output, numF + 1);
    
  3. 返回修改后的值:

    …
    if (! (dir = opendir(actual))) {
        return numF;
    }
    …
    
        …
        closedir(dir);
        return numF;
    }
    
  4. ... 并更改函数的调用方式。

我还强烈建议不要混合语言(坚持使用英语编写代码和注释!),并花时间清晰一致地格式化您的代码(尤其是缩进和间距)。您的代码的读者(包括您自己!)会感谢您 — 事实上,格式清晰的代码不是可有可无的,几乎所有地方都毫无异常(exception)强制执行。

关于递归统计目录中的所有文件(包括子目录中的文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56915078/

相关文章:

c - 快速排序跳过一个元素

在 Eclipse 中从现有源代码创建项目

c - 是否有一个标准的 C 函数来获取 Double 变量的绝对值

linux - root 用户的 Chef 客户端权限被拒绝

linux - 在shell脚本中处理多行变量

arrays - 将字符串添加到数组 C(指针)

python - 属性错误 : 'module' object has no attribute python

c - 对大页面使用 mmap 和 madvise

linux - pwd|sed -e 是什么意思?

c - 在 C 中不使用 fseek 移动文件位置