Skip to content

Instantly share code, notes, and snippets.

@davidrusu
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrusu/265b9d77a2b751f914d2 to your computer and use it in GitHub Desktop.
Save davidrusu/265b9d77a2b751f914d2 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#define error(msg) printf("%s\n", msg); exit(1);
void showdir(char *, char *);
int main(int argc, char **argv) {
char *dir;
if (argc == 1){
dir = get_current_dir_name();
} else if (argc >= 2) {
dir = argv[1];
}
showdir("", dir);
}
void showdir(char *prefix, char *dir_name) {
DIR *dir_stream = opendir(dir_name);
printf("%s %s\n", prefix, dir_name);
struct dirent *direntp;
char *prefix_buf = malloc(strlen(prefix) + 3);
strcat(prefix_buf, prefix);
strcat(prefix_buf, " |");
while ((direntp = readdir(dir_stream)) != NULL) {
if (strcmp(direntp->d_name, ".") == 0
|| strcmp(direntp->d_name, "..") == 0 ) {
continue;
}
if (direntp->d_type == DT_DIR) {
char *new_dir_name = malloc(strlen(dir_name) + strlen(direntp->d_name) + 2);
strcat(new_dir_name, dir_name);
strcat(new_dir_name, "/");
strcat(new_dir_name, direntp->d_name);
showdir(prefix_buf, new_dir_name);
} else {
printf("%s-%s\n", prefix_buf, direntp->d_name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment