Cooler_

recursive open dir

Jun 3rd, 2012
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 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. static void
  12. list_dir (char * dir2find)
  13. {
  14.  DIR *d;
  15.  char *dir_name=(char *)malloc(sizeof(char)*512);
  16.  
  17.   if( *(dir2find+0) != '/')
  18.   {
  19.    getcwd(dir_name, 512);
  20.    strncat(dir_name,"/",512);
  21.   }
  22.   strncat(dir_name,dir2find,512);
  23.   d=opendir(dir_name);
  24.  
  25.     if(!d)
  26.     {
  27.      fprintf(stderr, "Cannot open directory '%s': %s\n", dir_name, strerror (errno));
  28.      exit(EXIT_FAILURE);
  29.     }
  30.  
  31.     while(1)
  32.     {
  33.      struct dirent *entry;
  34.      const char *d_name;
  35.  
  36.       entry = readdir(d);
  37.  
  38.       if(!entry)
  39.        break;
  40.        
  41.       d_name = entry->d_name;
  42.  
  43.       fprintf (stdout,"%s/%s\n", dir_name, d_name);
  44.  
  45.  
  46.  
  47.       if(entry->d_type & DT_DIR)
  48.       {      
  49.        if(*(d_name+0)!='.')
  50.        {
  51.         int path_length;
  52.         char path[PATH_MAX];
  53.  
  54.         path_length = snprintf(path, PATH_MAX, "%s/%s", dir_name, d_name);
  55.         fprintf(stdout,"Dir : %s \n",path);
  56.  
  57.         if(path_length >= PATH_MAX)
  58.         {
  59.          fprintf (stderr, "Path length has got too long.\n");
  60.          exit (EXIT_FAILURE);
  61.         }
  62.         list_dir(path);
  63.        }
  64.       }
  65.     }
  66.  
  67.     if(closedir(d))
  68.     {
  69.      fprintf (stderr, "Could not close '%s': %s\n",dir_name, strerror (errno));
  70.      exit (EXIT_FAILURE);
  71.     }
  72.  
  73.  free(dir_name);
  74. }
  75.  
  76. int main ()
  77. {
  78.  
  79.     list_dir ("TEST");
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment