In the previous article, we saw how to list all files in a particular directory. That program does not display the files of the subdirecties. Here we’ll see how to display the files of the current direcory and of the subdirectories. The directory stucture could be arbitarily nested. The program here will display the files in a tree structure.
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void list_dir(char *path, int indent) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
printf("Failed to open directory.\n");
return;
}
while ((entry = readdir(dir)) != NULL) {
if(entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
printf("%c%s\n", indent2, '-', entry->d_name);
char *new_path = (char *)malloc(strlen(path) + strlen(entry->d_name) + 1);
sprintf(new_path, "%s/%s", path, entry->d_name);
list_dir(new_path, indent + 1);
free(new_path);
}
} else {
printf("%c%s\n", indent2, '-', entry->d_name);
}
}
closedir(dir);
}
int main(void) {
printf("Current directory structure:\n");
list_dir(".", 1);
return 0;
}
The list_dir() recursive function displays all files in the current directory. And for all directories inside the current directory, this function calls itself recursively.
$ ls
file1.txt file2.txt file3.txt subdir1 subdir2
The above current directory has 3 files and two subdirectories. If we run the program in this directory we’ll see the following putput.
$ ./test
Current directory structure:
-file1.txt
-file2.txt
-file3.txt
-subdir1
-file1.txt
-subdir2
-file1.txt
-file2.txt
The post C Program to List All Files Including Subdirectories appeared first on QnA Plus.