Skip to content

Instantly share code, notes, and snippets.

@luishendrix92
Created July 25, 2024 23:03
Show Gist options
  • Save luishendrix92/0581399a0258cea82a5e98c76a86305d to your computer and use it in GitHub Desktop.
Save luishendrix92/0581399a0258cea82a5e98c76a86305d to your computer and use it in GitHub Desktop.
List directories recursively in C
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#define CURRENT_DIR "."
#define PARENT_DIR ".."
#define MAX_PATH 1024
void listdir(char *dirname, int level);
void printn(char *s, int n);
int main(void) {
listdir(CURRENT_DIR, 0);
return 0;
}
void listdir(char *dirname, const int level) {
DIR *directory;
if ((directory = opendir(dirname)) == NULL) {
fprintf(stderr, "listdir: error opening %s\n", dirname);
return;
}
printn("| ", level);
if (level > 0)
printf("|- ");
puts(dirname);
const struct dirent *entry;
while ((entry = readdir(directory)) != NULL) {
if (strcmp(entry->d_name, CURRENT_DIR) == 0 ||
strcmp(entry->d_name, PARENT_DIR) == 0)
continue;
if (entry->d_type == DT_DIR) {
if (strlen(dirname) + strlen(entry->d_name) + 2 > MAX_PATH) {
fprintf(stderr, "listdir: path name too long\n");
return;
}
char path[MAX_PATH];
snprintf(path, MAX_PATH, "%s/%s", dirname, entry->d_name);
listdir(path, level + 1);
} else {
printn("| ", level);
printf("|- %s\n", entry->d_name);
}
}
if (closedir(directory) == -1)
fprintf(stderr, "listdir: error closing %s\n", dirname);
}
void printn(char *s, const int n) {
for (int i = 0; i < n; i++)
printf("%s", s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment