Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <dirent.h>
- #include <sys/stat.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <sys/stat.h>
- #include <limits.h>
- #include <stdio.h>
- #include <string.h>
- enum { BASE_AMOUNT = 5 };
- int
- comp(const void *a, const void *b)
- {
- const char **str_a = (const char **)a;
- const char **str_b = (const char **)b;
- return strcasecmp(*str_a, *str_b);
- }
- void
- dir_traversal(char *path_root, char *saved_argv)
- {
- DIR *root_dir = opendir(path_root), *d;
- if (root_dir == NULL) {
- return;
- }
- struct stat st;
- struct dirent *entry;
- char buf[PATH_MAX];
- int dirs_amount = 0, curr_amount = BASE_AMOUNT;
- char **array = calloc(curr_amount, sizeof(*array));
- while ((entry = readdir(root_dir)) != NULL) {
- if (strlen(path_root) + strlen(entry->d_name) > sizeof(buf) - 1) {
- return;
- }
- snprintf(buf, sizeof(buf), "%s/%s", path_root, entry->d_name);
- if (lstat(buf, &st) == -1) {
- continue;
- }
- if (S_ISDIR(st.st_mode) == 1) {
- if (dirs_amount >= curr_amount-1) {
- curr_amount <<= 1;
- array = realloc(array, curr_amount * sizeof(*array));
- }
- array[dirs_amount++] = strdup(entry->d_name);
- }
- }
- qsort(array, dirs_amount, sizeof(*array), comp);
- closedir(root_dir);
- for (int i = 0; i < dirs_amount; ++i) {
- if (array[i] == NULL) {
- continue;
- }
- if (strcmp(array[i], ".") == 0 || strcmp(array[i], "..") == 0) {
- continue;
- }
- if (strlen(path_root) + strlen(array[i]) > sizeof(buf) - 1) {
- return;
- }
- snprintf(buf, sizeof(buf), "%s/%s", path_root, array[i]);
- if ((d = opendir(buf)) != NULL) {
- closedir(d);
- printf("cd %s\n", array[i]);
- free(array[i]);
- dir_traversal(buf, saved_argv);
- }
- }
- if (strcmp(path_root, saved_argv) != 0) {
- printf("cd ..\n");
- }
- return;
- }
- int
- main(int argc, char *argv[])
- {
- dir_traversal(argv[1], argv[1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement