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?