Cooler_

recursive open files... lol

Jun 3rd, 2012
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 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.  
  19.   if( dir2find[0] != '/')
  20.   {
  21.    getcwd(dir_name, PATH_MAX);
  22.    strncat(dir_name,"/",PATH_MAX);
  23.   }
  24.   strncat(dir_name,dir2find,PATH_MAX);
  25.   d=opendir(dir_name);
  26.  
  27.     if(!d)
  28.     {
  29.      fprintf(stderr, "Cannot open directory '%s': %s\n", dir_name, strerror (errno));
  30.      exit(EXIT_FAILURE);
  31.     }
  32.  
  33.     while(1)
  34.     {
  35.      struct dirent *entry;
  36.      const char *d_name;
  37.  
  38.      tmp=(char *)malloc(PATH_MAX*sizeof(char));
  39.      entry=readdir(d);
  40.  
  41.       if(!entry)
  42.        break;
  43.        
  44.       d_name = entry->d_name;
  45.  
  46.       if(entry->d_type & DT_DIR)
  47.       {      
  48.        if(d_name[0]!='.')
  49.        {
  50.         int path_length;
  51.         char path[PATH_MAX];
  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);
  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=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