Cooler_

list files and subfiles...

Jun 2nd, 2012
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <dirent.h>
  7. #include <limits.h>
  8. #include <unistd.h>
  9.  
  10.  
  11. char **list_dir(char * dir2find)
  12. {
  13.  DIR *d;
  14.  char *dir_name=(char *)malloc(sizeof(char)*512);
  15.  char **list=(char **)malloc(1*sizeof(char *));
  16.  short counter=0;
  17.  
  18.  
  19.   if( *(dir2find+0) != '/')
  20.   {
  21.    getcwd(dir_name, 512);
  22.    strncat(dir_name,"/",512);
  23.    strncat(dir_name,dir2find,512);
  24.   } else strcpy(dir_name,dir2find);
  25.  
  26.   HELL:
  27.  
  28.   d=opendir(dir_name);
  29.  
  30.     if(!d)
  31.     {
  32.      fprintf(stderr, "Cannot open directory '%s': %s\n", dir_name, strerror (errno));
  33.      exit(EXIT_FAILURE);
  34.     }
  35.     while(1)
  36.     {
  37.      struct dirent *entry;
  38.      const char *d_name;
  39.  
  40.       entry = readdir(d);
  41.  
  42.       if(!entry)
  43.       {
  44.  
  45.        break;
  46.       }  
  47.       d_name = entry->d_name;
  48.  
  49.        fprintf(stdout,"%s/%s\n", dir_name, d_name);
  50.  
  51.       if(entry->d_type & DT_DIR)
  52.       {      
  53.        if(*(d_name+0)!='.')
  54.        {
  55.  
  56.         char *tmp=dir_name;
  57.         snprintf(tmp, 511, "%s/%s", dir_name, d_name);
  58.         list[counter]=tmp;
  59.         counter++;
  60.         list=realloc(list,(counter+1)*sizeof(char *));
  61.         goto HELL;
  62.        }
  63.       } else {
  64.        char *tmp=dir_name;
  65.        sprintf (tmp,"%s/%s\n", dir_name, d_name);
  66.        list[counter]=tmp;
  67.        counter++;
  68.        list=realloc(list,(counter+1)*sizeof(char *));
  69.       }
  70.      
  71.     }
  72.  
  73.     if(closedir(d))
  74.     {
  75.      fprintf (stderr, "Could not close '%s': %s\n",dir_name, strerror (errno));
  76.      exit (EXIT_FAILURE);
  77.     }
  78.  
  79.  puts("exit func");
  80.  free(dir_name);
  81.  return list;
  82. }
  83.  
  84. int
  85. main()
  86. {
  87.  
  88.  char **test= (char **)malloc(1*sizeof(char *));
  89.  
  90.  test=list_dir ("TEST");
  91.  puts("ok");
  92.  fprintf(stdout,"%s \n",test[0]);
  93.  free(test);
  94.  
  95.  return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment