In this code, I am getting all the subdirectories paths from a directory. It is working fine but I want to add something more and that is to count all the subdirectories and print them. How to do this in this function. I used the count
variable to make it work but the result is like this.
Given result:
/home/runner/TestC1/file
15775232
/home/runner/TestC1/dsf
15775233
/home/runner/TestC1/main.c
15775234
/home/runner/TestC1/main
15775235
Expected result:
/home/runner/TestC1/file
/home/runner/TestC1/dsf
/home/runner/TestC1/main.c
/home/runner/TestC1/main
Counted: 4 subdirectories.
Code
void listdir(void){
DIR *dir;
struct dirent *entry;
size_t count;
if (!(dir = opendir(path))) {
perror ("opendir-path not found");
return;
}
while ((entry = readdir(dir)) != NULL) {
char *name = entry->d_name;
if (entry->d_type == DT_DIR)
if (!strcmp(name, ".") || !strcmp(name, ".."))
continue;
snprintf (path1, 100, "%s/%s\n", path, name);
printf("%s", path1);
printf("%zu\n", count);
count++;
}
closedir (dir);
}