Solved exercise 2 - create a simple tree program clone

This commit is contained in:
Fabio Scotto di Santolo
2025-06-30 22:25:31 +02:00
parent 7bc220f92c
commit a629f9de01
6 changed files with 162 additions and 0 deletions

35
exercises/tree/tree.c Normal file
View File

@@ -0,0 +1,35 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include "tree.h"
int print_tree(const char *path, int depth) {
DIR *dir = opendir(path);
if (!dir) return -1;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Skip . and ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
for (int i = 0; i < depth; i++) printf(" ");
printf("|-- %s\n", entry->d_name);
// Construct full path
char full_path[4096];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat st;
if (stat(full_path, &st) == 0 && S_ISDIR(st.st_mode)) {
print_tree(full_path, depth + 1);
}
}
closedir(dir);
return 0;
}