Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions 07_trees/c/01_filesystem_dfs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int filter(const struct dirent *entry) {
return strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0;
}

void printnames(const char *dir) {
struct dirent **entries;
int count = scandir(dir, &entries, filter, alphasort);

if (count < 0) {
perror("scandir");
return;
}

for (int i = 0; i < count; i++) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", dir, entries[i]->d_name);

struct stat sb;
if (stat(path, &sb)) {
perror("stat");
free(entries[i]);
continue;
}

if (S_ISREG(sb.st_mode)) {
printf("%s\n", entries[i]->d_name);
} else if (S_ISDIR(sb.st_mode)) {
printnames(path);
}

free(entries[i]);
}
free(entries);
}

int main() {
printnames("pics");
return 0;
}