void count(char *dir, int levels, int *filecount, int *dircount) {
struct dirent *dp;
DIR *fd;
if ((fd=opendir(dir))==NULL) {
fprintf(stderr, "count: can't open %s\ncount stopped.", dir);
exit(0);
}
while((dp = readdir(fd))!=NULL){
if(!strcmp(dp->d_name, ".")||!strcmp(dp->d_name, ".."))
continue;
if(dp->d_type==DT_REG){ /* Regular file */
(*filecount)++;
}
if(dp->d_type==DT_DIR){ /* Directory */
(*dircount)++;
if(levels>0){
count(dp->d_name,levels-1,filecount,dircount);
}
}
}
closedir(fd);
}
这是我试图在 C 中实现的一个函数,它递归地计算某个文件夹中的目录和文件的数量,仅针对某个深度
示例:我有一个文件夹“a”,其中包含 2 个子文件夹“b”、“c”,我写的是级别 1,它只会计算“a”中的文件,以及“a/b”和“a/c”中的文件,但它不会在例如“a/b/d”中进一步查找。
我不知道为什么,但是当我调用 main count("a",1,files,directories); 它打开“a”,计算其中的内容,但无法打开“b”和“c”,并在屏幕上打印来自 fd=opendir(dir); 的 fprintef stderr;
有谁知道为什么?