Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1 │ #include <stdio.h>
- 2 │ #include <dirent.h>
- 3 │ #include <sys/types.h>
- 4 │ #include <sys/stat.h>
- 5 │ #include <fcntl.h>
- 6 │ #include <stdlib.h>
- 7 │ #include <limits.h>
- 8 │ #include <ctype.h>
- 9 │ #include <unistd.h>
- 10 │ #include <string.h>
- 11 │
- 12 │ int cmp(const void* a, const void* b) {
- 13 │ const char* A = *(const char**)a;
- 14 │ const char* B = *(const char**)b;
- 15 │ return strcasecmp(A, B);
- 16 │ }
- 17 │
- 18 │ char gbuf[PATH_MAX];
- 19 │
- 20 │ void traverse(char* dir, char* myname, int size) {
- 21 │ DIR* d = opendir(dir);
- 22 │ if (d) {
- 23 │ char** names = NULL;
- 24 │ int a = 0, u = 0;
- 25 │
- 26 │ if (myname) {
- 27 │ printf("cd %s\n", myname);
- 28 │ }
- 29 │
- 30 │ struct dirent* dd;
- 31 │ while ((dd = readdir(d))) {
- 32 │ if (strcmp(dd->d_name, ".") && strcmp(dd->d_name, "..")) {
- 33 │ char buf[PATH_MAX];
- 34 │ if (snprintf(buf, sizeof(buf), "%s/%s", dir, dd->d_name) < sizeof(buf)) {
- 35 │ struct stat stb;
- 36 │ if (lstat(buf, &stb) >= 0 && S_ISDIR(stb.st_mode)) {
- 37 │ if (u == a) {
- 38 │ if (!(a *= 2)) a = 64;
- 39 │ names = realloc(names, a * sizeof(names[0]));
- 40 │ if (!names) abort();
- 41 │ }
- 42 │ names[u++] = strdup(dd->d_name);
- 43 │ }
- 44 │ }
- 45 │ }
- 46 │ }
- 47 │ closedir(d);
- 32 │ if (strcmp(dd->d_name, ".") && strcmp(dd->d_name, "..")) {
- 33 │ char buf[PATH_MAX];
- 34 │ if (snprintf(buf, sizeof(buf), "%s/%s", dir, dd->d_name) < sizeof(buf)) {
- 35 │ struct stat stb;
- 36 │ if (lstat(buf, &stb) >= 0 && S_ISDIR(stb.st_mode)) {
- 37 │ if (u == a) {
- 38 │ if (!(a *= 2)) a = 64;
- 39 │ names = realloc(names, a * sizeof(names[0]));
- 40 │ if (!names) abort();
- 41 │ }
- 42 │ names[u++] = strdup(dd->d_name);
- 43 │ }
- 44 │ }
- 45 │ }
- 46 │ }
- 47 │ closedir(d);
- 48 │
- 49 │ qsort(names, u, sizeof(names[0]), cmp);
- 50 │ for (int i = 0; i < u; ++i) {
- 51 │ int new_size = size + 1 + strlen(names[i]);
- 52 │ dir[size] = '/';
- 53 │ memcpy(dir + size + 1, names[i], strlen(names[i]) + 1);
- 54 │ traverse(dir, names[i], new_size);
- 55 │ dir[size] = '\0';
- 56 │ }
- 57 │
- 58 │ free(names);
- 59 │
- 60 │ if (myname) {
- 61 │ printf("cd ..\n");
- 62 │ }
- 63 │ }
- 64 │ }
- 65 │
- 66 │ int main(int argc, char* argv[]) {
- 67 │ memset(gbuf, 0, sizeof(gbuf));
- 68 │ if (strlen(argv[1]) < sizeof(gbuf)) {
- 69 │ memcpy(gbuf, argv[1], strlen(argv[1]));
- 70 │ traverse(gbuf, NULL, strlen(gbuf));
- 71 │ }
- 72 │ }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement