Advertisement
wowonline

Untitled

Dec 11th, 2021
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <dirent.h>
  2. #include <sys/stat.h>
  3. #include <stdlib.h>
  4. #include <strings.h>
  5. #include <sys/stat.h>
  6. #include <limits.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9.  
  10. enum { BASE_AMOUNT = 5 };
  11.  
  12. int
  13. comp(const void *a, const void *b)
  14. {
  15.     const char **str_a = (const char **)a;
  16.     const char **str_b = (const char **)b;
  17.     return strcasecmp(*str_a, *str_b);
  18. }
  19.  
  20. void
  21. dir_traversal(char *path_root, char *saved_argv)
  22. {
  23.     DIR *root_dir = opendir(path_root), *d;
  24.     if (root_dir == NULL) {
  25.         return;
  26.     }
  27.     struct stat st;
  28.     struct dirent *entry;
  29.     char buf[PATH_MAX];
  30.  
  31.     int dirs_amount = 0, curr_amount = BASE_AMOUNT;
  32.     char **array = calloc(curr_amount, sizeof(*array));
  33.     while ((entry = readdir(root_dir)) != NULL) {
  34.         if (strlen(path_root) + strlen(entry->d_name) > sizeof(buf) - 1) {
  35.             return;
  36.         }
  37.         snprintf(buf, sizeof(buf), "%s/%s", path_root, entry->d_name);
  38.         if (lstat(buf, &st) == -1) {
  39.             continue;
  40.         }
  41.         if (S_ISDIR(st.st_mode) == 1) {
  42.             if (dirs_amount >= curr_amount-1) {
  43.                 curr_amount <<= 1;
  44.                 array = realloc(array, curr_amount * sizeof(*array));
  45.             }
  46.             array[dirs_amount++] = strdup(entry->d_name);
  47.         }
  48.     }
  49.     qsort(array, dirs_amount, sizeof(*array), comp);
  50.  
  51.     closedir(root_dir);
  52.     for (int i = 0; i < dirs_amount; ++i) {
  53.         if (array[i] == NULL) {
  54.             continue;
  55.         }
  56.         if (strcmp(array[i], ".") == 0 || strcmp(array[i], "..") == 0) {
  57.             continue;
  58.         }
  59.         if (strlen(path_root) + strlen(array[i]) > sizeof(buf) - 1) {
  60.             return;
  61.         }
  62.         snprintf(buf, sizeof(buf), "%s/%s", path_root, array[i]);
  63.         if ((d = opendir(buf)) != NULL) {
  64.             closedir(d);
  65.             printf("cd %s\n", array[i]);
  66.             free(array[i]);
  67.             dir_traversal(buf, saved_argv);
  68.         }
  69.     }
  70.     if (strcmp(path_root, saved_argv) != 0) {
  71.         printf("cd ..\n");
  72.     }
  73.     return;
  74. }
  75.  
  76. int
  77. main(int argc, char *argv[])
  78. {
  79.     dir_traversal(argv[1], argv[1]);
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement