0
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);
}

This is a function that I'm trying to implement in C that recursively counts the number of directories and files in a certain folde, only for a certain depth

example: I have a folder "a" with 2 subfolders "b","c" and I write level 1, it will only count the files in "a", and also in "a/b" and "a/c", but it will not look further in, for instance, "a/b/d".

I don't know why, but when I call in main count("a",1,files,directories); it opens "a", counts what in it, but it can't open "b" and "c", and it prints on the screen the fprintef stderr from fd=opendir(dir);

Does anyone know why?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Place a `perror("opendir() failed");` just before `fprintf(stderr, "count: can't open %s\ncount stopped.", dir);`. – alk Dec 02 '16 at 13:56
  • I wonder if there's a canonical "using `readdir()` doesn't work with nested directories" Q&A here on SO. There probably is as this is a common problem. – Jonathan Leffler Dec 02 '16 at 15:13

1 Answers1

3

Because you need to use the right pathname when descending:

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

Remember that all relative path names are resolved from the current directory.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69