【发布时间】:2016-12-02 13:44:55
【问题描述】:
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;
有人知道为什么吗?
【问题讨论】:
-
在
fprintf(stderr, "count: can't open %s\ncount stopped.", dir);之前放置一个perror("opendir() failed");。 -
我想知道这里是否有规范的“使用
readdir()不适用于嵌套目录”问答。可能是因为这是一个常见问题。