【问题标题】:I can't open subfolders of a certain folder [duplicate]我无法打开某个文件夹的子文件夹[重复]
【发布时间】: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() 不适用于嵌套目录”问答。可能是因为这是一个常见问题。

标签: c linux dirent.h


【解决方案1】:

因为降序时需要使用正确的路径名:

char *subpath = malloc(strlen(dir)+strlen(dp->d_name)+1);
strcpy(subpath,dir);
strcat(subpath,dp->d_name);
count(subpath,...);
free(subpath);

请记住,所有相对路径名都是从当前目录解析的。

【讨论】:

  • 哦,是的...忘记了。谢谢您的帮助!它现在可以工作了:)
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
相关资源
最近更新 更多