Advertisement
Guest User

Untitled

a guest
May 7th, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /*
  2.    Jaren Rowan
  3.    COMP 322/L
  4.    Project 5
  5. */
  6.  
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <sys/types.h>
  10. #include <string.h>
  11. #include <errno.h>
  12. #include <dirent.h>
  13. #include <limits.h>
  14.  
  15. static void
  16. listdir (const char * dir_name){
  17.     DIR * dir;
  18.  
  19.     /* Open the directory specified by "dir_name". */
  20.     dir = opendir (dir_name);
  21.  
  22.     /* Check it was opened. */    
  23.     if (! dir){
  24.         fprintf (stderr, "Cannot open directory '%s': %s\n", dir_name, strerror (errno));
  25.         exit (EXIT_FAILURE);
  26.     }
  27.    
  28.     while (1){
  29.         struct dirent * entry;
  30.         const char * d_name;
  31.  
  32.         /* "Readdir" gets subsequent entries from "d". */
  33.         entry = readdir (dir);
  34.         if (! entry) {
  35.             /* There are no more entries in this directory, so break
  36.                out of the while loop. */
  37.             break;
  38.         }
  39.         d_name = entry->d_name;
  40.  
  41.         if(entry->d_type & DT_DIR) {
  42.  
  43.             /* Check that the directory is not "d" or d's parent. */
  44.            
  45.             if(strcmp (d_name, "..") != 0 && strcmp (d_name, ".") != 0) {
  46.                 int path_length;
  47.                 char path[PATH_MAX];
  48.  
  49.                 path_length = snprintf (path, PATH_MAX,"%s/%s", dir_name, d_name);
  50.                 printf ("%s\n", d_name);
  51.                 if (path_length >= PATH_MAX) {
  52.                     fprintf (stderr, "Path length has got too long.\n");
  53.                     exit (EXIT_FAILURE);
  54.                 }
  55.                 /* Recursively call "listdir" with the next. */
  56.                 listdir (path);
  57.             }
  58.          }
  59.     }
  60.     /* After going through all the entries, close the directory. */
  61.     if (closedir (dir)) {
  62.         fprintf (stderr, "Could not close '%s': %s\n",dir_name, strerror (errno));
  63.         exit (EXIT_FAILURE);
  64.     }
  65. }
  66.  
  67. int main(int argc, char **argv) {
  68.   int x = 1;
  69.  
  70.   if (argc == 1)
  71.     listdir(".");
  72.  
  73.   while (++x <= argc){
  74.     listdir(argv[x-1]);
  75.   }
  76.  
  77.   return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement