Advertisement
Guest User

file list helper

a guest
Apr 25th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1.  
  2. #include "flist.h"
  3.  
  4. int main() {
  5.    
  6.     FList *f;
  7.    
  8.     f = init_file_list("/");
  9.     get_file_list(f);
  10.     print_file_list(f);
  11.     printf("file count: %li", f->count);
  12.     free_file_list(f);
  13.  
  14.     return 0;
  15. }
  16.  
  17.  
  18. FList *init_file_list(const char *path){
  19.     FList *f = (FList*)malloc(sizeof(FList));
  20.     f->count = 0;
  21.     f->path = (char*)malloc(sizeof(char)*(strlen(path)+1));
  22.     strcpy(f->path,path);
  23.     return f;
  24. }
  25.  
  26. void get_file_list(FList *f){
  27.     size_t index = 0;
  28.     recurse_dir(f->path, &(f->files), &(f->count));
  29.     f->files = (char**)malloc(f->count*sizeof(char*));
  30.     recurse_dir(f->path, &(f->files), &index);
  31. }
  32.  
  33. void print_file_list(FList *f){
  34.     size_t i;
  35.     for (i = 0; i < f->count; i++) {
  36.         printf("%s\n", f->files[i]);
  37.     }
  38. }
  39.  
  40. void free_file_list(FList *f){
  41.     size_t i;
  42.     for (i = 0; i < f->count; i++) {
  43.         free((void*)(f->files)[i]);
  44.     }
  45.     free((void*)f->files);
  46.     free((void*)f);
  47. }
  48.  
  49. void recurse_dir(char *path, char ***files, size_t *index){
  50.    
  51.     char *newpath;
  52.     struct dirent *ent;
  53.     DIR *dir = opendir(path);
  54.    
  55.     if (dir == NULL) {
  56.         perror("erro ao abrir diretorio");
  57.         return;
  58.     }
  59.  
  60.     while ((ent = readdir(dir)) != NULL){
  61.         if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 && (ent->d_name[0] != '.')) {
  62.             build_path(&(newpath), path, ent->d_name);
  63.             recurse_dir(newpath, files, index);
  64.             free((void *)newpath);
  65.         }
  66.         else if (ent->d_type == DT_REG && ent->d_name[0] != '.') {
  67.             if(*files != NULL){
  68.                 build_path(&(newpath), path, ent->d_name);
  69.                 *((*files) + *index) = newpath;
  70.             }
  71.             (*index)++;
  72.         }
  73.     }
  74.     closedir(dir);
  75. }
  76.  
  77. void build_path(char **fullpath, const char *path, const char *filename){
  78.     *fullpath = malloc(strlen(path) + strlen(filename) + 2);
  79.     if(*fullpath == NULL){
  80.         perror("erro ao alocar memoria para os enderecos de arquivo");
  81.         exit(1);
  82.     }
  83.     strcpy(*fullpath, path);
  84.     strcat(*fullpath, "/");
  85.     strcat(*fullpath, filename);
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement