gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:54 25 4
gpt4 key购买 nike

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

基础/目录 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com