Skip to content

Instantly share code, notes, and snippets.

@mattn
Forked from cho45/c.c
Created January 19, 2009 04:14
Show Gist options
  • Save mattn/48871 to your computer and use it in GitHub Desktop.
Save mattn/48871 to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct entry {
char* path;
struct entry* next;
} ENTRY;
ENTRY* downto (char* root, ENTRY* entry) {
DIR* dir;
printf("downto %s\n", root);
dir = opendir(root);
if (dir == NULL) return NULL;
struct dirent* ent;
char* path;
while ((ent = readdir(dir)) != NULL) {
path = calloc(strlen(root) + strlen(ent->d_name) + 2, sizeof(char));
sprintf(path, "%s/%s", root, ent->d_name);
if (strcmp(ent->d_name, ".") == 0) continue;
if (strcmp(ent->d_name, "..") == 0) continue;
entry->next = (ENTRY*)malloc(sizeof(ENTRY));
entry = entry->next;
entry->next = NULL;
entry->path = path;
// printf("%s\n", entry->path);
struct stat s;
stat(path, &s);
// printf("%s %d\n", path, S_ISDIR(s.st_mode));
if (S_ISDIR(s.st_mode)) {
entry = downto(path, entry);
}
// free(path);
}
closedir(dir);
return entry;
}
int main (int argc, char* argv[]) {
ENTRY* top_entry;
ENTRY* entry;
if (argc != 2) {
fprintf(stderr, "usage: %s [path]", argv[0]);
return -1;
}
top_entry = (ENTRY*)malloc(sizeof(ENTRY));
memset(top_entry, 0, sizeof(ENTRY));
//downto("/home/cho45/blosxom-test-data", &entries);
downto(argv[1], top_entry);
entry = top_entry;
while ((entry = entry->next)) {
printf("%s\n", entry->path);
}
while (top_entry) {
entry = top_entry;
if (entry->path) free(entry->path);
top_entry = entry->next;
free(entry);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment