Advertisement
Guest User

Untitled

a guest
Oct 5th, 2015
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/file.h>
  6. #include <sys/stat.h>
  7. #include <sys/types.h>
  8. #include <limits.h>
  9. #include <ctype.h>
  10. #include <dirent.h>
  11. #include <string.h>
  12.  
  13. enum { buf_size = 100 };
  14.  
  15. void dfs(char *path_to_dir, char *printing_name, int need_to_be_printed) {
  16.     DIR *d;
  17.     if (!(d = opendir(path_to_dir))) {
  18.         return;
  19.     }
  20.     if (need_to_be_printed) {
  21.         printf("cd %s\n", printing_name);
  22.     }
  23.  
  24.     char name[buf_size][PATH_MAX], result_path[buf_size][PATH_MAX]; // плохо!
  25.  
  26.     struct dirent *entry;
  27.     struct stat s;
  28.     char *dv = "/";
  29.     if (!strcmp(path_to_dir, "/")) {
  30.         dv = "";
  31.     }
  32.     int cnt = 0;
  33.     while ((entry = readdir(d))) {
  34.         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
  35.             continue;
  36.         }
  37.         snprintf(name[cnt++], PATH_MAX, "%s", entry->d_name);
  38.         snprintf(result_path[cnt - 1], PATH_MAX, "%s%s%s", path_to_dir, dv, entry->d_name);
  39.         if (lstat(result_path[cnt - 1], &s) < 0) {
  40.             cnt--;
  41.             continue;
  42.         }
  43.         if (!(S_ISDIR(s.st_mode))) {
  44.             cnt--;
  45.         }
  46.     }
  47.  
  48.     closedir(d);
  49.  
  50.     int i, j, tmp;
  51.     int order[buf_size];
  52.     for (i = 0; i < cnt; i++) {
  53.         order[i] = i;
  54.     }
  55.     for (i = 0; i < cnt; i++)
  56.         for (j = i + 1; j < cnt; j++)
  57.         if (strcasecmp(name[order[i]], name[order[j]]) > 0) {
  58.             tmp = order[i];
  59.             order[i] = order[j];
  60.             order[j] = tmp;
  61.         }
  62.  
  63.     for (i = 0; i < cnt; i++) {
  64.         snprintf(result_path[i], PATH_MAX, "%s%s%s", path_to_dir, dv, name[order[i]]);
  65.         dfs(result_path[i], name[order[i]], 1);
  66.     }
  67.     if (need_to_be_printed) {
  68.         printf("cd ..");
  69.     }
  70. }
  71.  
  72. int main(int argc, char *argv[])
  73. {
  74.     char *start = "";
  75.     dfs(argv[1], start, 0);
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement