Reputation: 281
I'm doing a function that counts the number of files in a directory (including subdirectories and files inside that subdirectory). For example:
Base/Dir 1/Dir 1.1
Dir 1 has: hi.txt, hi2.txt
Dir 1.1 has: hi3.txt, hi4.txt, hi5.txt
So the output for number of files in Base should be 7 (ignoring . and ..)
The output for number of files in Dir 1 should be 6
The output for number of files in Dir 2 should be 3
This is what i've tried to do.
void recorrido(const char *actual, int indent, int op, char * output,int numF)
{
DIR *dir;
struct dirent *entrada;
char path[PATH_MAX+1];
char path2[PATH_MAX+1];
if (!(dir = opendir(actual))){
return;
}
while ((entrada = readdir(dir)) != NULL)
{
if (entrada->d_type == DT_DIR) //Directory
{
if ((strcmp(entrada->d_name, ".") != 0) && (strcmp(entrada->d_name, "..") != 0)) //Ignore . and ..
{
strcpy(path, actual);
strcat(path, "/");
strcat(path, entrada->d_name);
recorrido(path, indent + 2,op,output,numF++);
printf("Number of files for %s is %d", path, numF);
}
}
}
else if (entrada->d_type != DT_DIR){ //just file
if (strcmp(actual, "") == 0){
strcpy(path2, "./");
strcat(path2, entrada->d_name);
strcpy(actual, path2);
}
else
{
strcpy(path2, actual);
strcat(path2, "/");
strcat(path2, entrada->d_name);
//printf("File path is %s\n",path2);
numF++;
}
}
closedir(dir);
}
I have issues printing the proper number of files for each directory, if I have 2 folders inside of base (test 1 and test 2) it will take in account those folders but if I have something inside test 1 it will ignore it.
Upvotes: 1
Views: 73
Reputation: 545865
As noted in the comments, you need to return the incremented value.
Change the function signature:
int recorrido(const char *actual, int indent, int op, char *output, int numF)
Change how the function calls itself:
numF = recorrido(path, indent + 2, op, output, numF + 1);
Return the modified value:
…
if (! (dir = opendir(actual))) {
return numF;
}
…
…
closedir(dir);
return numF;
}
… and change how the function is called.
I also strongly suggest not mixing language (stick to English for code and comments!), and to spend time formatting your code cleanly and consistently (especially indentation and spacing). The readers of your code (including yourself!) will thank you — in fact, cleanly formatted code isn’t optional, it’s enforced without exception virtually everywhere.
Upvotes: 1