Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <dirent.h>
- #include <stdlib.h>
- #include <memory.h>
- #include <stdio.h>
- #include <sys/stat.h>
- int cmp(const void *a, const void *b)
- {
- return strcasecmp(*((char**) a), *((char**) b));
- }
- void scan_path(char *path, int len, DIR *dir)
- {
- static int counter = 0;
- struct dirent *ent;
- size_t size = 1;
- char **buf = calloc(size, sizeof(*buf));
- size_t i = 0;
- while ((ent = readdir(dir)) != NULL) {
- if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
- struct stat st;
- int name_len = snprintf(path + len, (size_t) (PATH_MAX - len), "/%s", ent->d_name);
- if (name_len < PATH_MAX - len && lstat(path, &st) != -1 && S_ISDIR(st.st_mode)) {
- if (i == size) {
- size *= 2;
- buf = realloc(buf, size*sizeof(*buf));
- }
- buf[i] = strdup(ent->d_name);
- i++;
- }
- }
- }
- closedir(dir);
- qsort(buf, i, sizeof(*buf), cmp);
- for (int j = 0; j < i; j++) {
- int name_len = snprintf(path + len, (size_t) (PATH_MAX - len), "/%s", buf[j]);
- if ((dir = opendir(path)) != NULL) {
- printf("cd %s\n", buf[j]);
- free(buf[j]);
- scan_path(path, len + name_len, dir);
- } else {
- free(buf[j]);
- }
- }
- if (counter) {
- printf("cd ..\n");
- }
- counter++;
- free(buf);
- }
- int main(int argc, char *argv[])
- {
- if (argc < 2) {
- return 1;
- }
- char *path = argv[1];
- DIR *dir;
- if ((dir = opendir(path)) != NULL) {
- char path1[PATH_MAX + 1];
- sprintf(path1, "%s", path);
- scan_path(path1, (int) strlen(path1), dir);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement