Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <dirent.h>
  2. #include <stdlib.h>
  3. #include <memory.h>
  4. #include <stdio.h>
  5. #include <sys/stat.h>
  6.  
  7.  
  8. int cmp(const void *a, const void *b)
  9. {
  10.     return strcasecmp(*((char**) a), *((char**) b));
  11. }
  12.  
  13.  
  14. void scan_path(char *path, int len, DIR *dir)
  15. {
  16.     static int counter = 0;
  17.     struct dirent *ent;
  18.     size_t size = 1;
  19.     char **buf = calloc(size, sizeof(*buf));
  20.     size_t i = 0;
  21.     while ((ent = readdir(dir)) != NULL) {
  22.         if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
  23.             struct stat st;
  24.             int name_len = snprintf(path + len, (size_t) (PATH_MAX - len), "/%s", ent->d_name);
  25.             if (name_len < PATH_MAX - len && lstat(path, &st) != -1 && S_ISDIR(st.st_mode)) {
  26.                 if (i == size) {
  27.                     size *= 2;
  28.                     buf = realloc(buf, size*sizeof(*buf));
  29.                 }
  30.                 buf[i] = strdup(ent->d_name);
  31.                 i++;
  32.             }
  33.         }
  34.     }
  35.     closedir(dir);
  36.     qsort(buf, i, sizeof(*buf), cmp);
  37.     for (int j = 0; j < i; j++) {
  38.         int name_len = snprintf(path + len, (size_t) (PATH_MAX - len), "/%s", buf[j]);
  39.         if ((dir = opendir(path)) != NULL) {
  40.             printf("cd %s\n", buf[j]);
  41.             free(buf[j]);
  42.             scan_path(path, len + name_len, dir);
  43.         } else {
  44.             free(buf[j]);
  45.         }
  46.     }
  47.     if (counter) {
  48.         printf("cd ..\n");
  49.     }
  50.     counter++;
  51.     free(buf);
  52. }
  53.  
  54.  
  55. int main(int argc, char *argv[])
  56. {
  57.     if (argc < 2) {
  58.         return 1;
  59.     }
  60.     char *path = argv[1];
  61.     DIR *dir;
  62.     if ((dir = opendir(path)) != NULL) {
  63.         char path1[PATH_MAX + 1];
  64.         sprintf(path1, "%s", path);
  65.         scan_path(path1, (int) strlen(path1), dir);
  66.     }
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement