Cooler_

test recursive

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