Skip to content

Instantly share code, notes, and snippets.

@cho45
Created January 18, 2009 20:15
Show Gist options
  • Save cho45/48753 to your computer and use it in GitHub Desktop.
Save cho45/48753 to your computer and use it in GitHub Desktop.
//#!gcc -g -O0 -Wall c.c && ./a.out #
#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;
}
void destroy_entries (ENTRY* entries) {
ENTRY* entry;
ENTRY* next;
entry = entries->next;
while (1) {
free(entry->path);
next = entry->next;
free(entry);
entry = next;
if (!entry) break;
}
}
int main (int argc, char* argv[]) {
ENTRY entries;
ENTRY* entry;
downto("/home/cho45/blosxom-test-data", &entries);
entry = &entries;
while ((entry = entry->next)) {
printf("%s\n", entry->path);
}
destroy_entries(&entries);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment