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
this code is so bad… indent2 is not a real declaration of variable since u call it “indent” on the function, d_type is not cross platform so probably wont work for a lot of people.
and the if blocks are all wrong lol, its better to have the if that checks for “.” and “..” first then inside it the if -else block that checks for directory or file. then you can declare new_path for both of them and have the full path for further usage. took me 1 hour to fix your terrible code
lolol can you share the fixed code pls?
Nice and helpful article to learn C file handling….