2

im looking for a code who will recursively list all directories and files of a directory given on argument in C programming, ive find an interresting code (below) but I dont understand the snprintf function and particulary the "/", I would prefer to use strcat or other system function to override the sprintf function but I dont see how since I dont understand what the snprintf do here. Heres the code:

int is_directory_we_want_to_list(const char *parent, char *name) {
    struct stat st_buf;
    if (!strcmp(".", name) || !strcmp("..", name))
        return 0;

    char *path = alloca(strlen(name) + strlen(parent) + 2);
    sprintf(path, "%s/%s", parent, name);
    stat(path, &st_buf);
    return S_ISDIR(st_buf.st_mode);
}

int list(const char *name) {
    DIR *dir = opendir(name);
    struct dirent *ent;

    while (ent = readdir(dir)) {
        char *entry_name = ent->d_name;
        printf("%s\n", entry_name);

        if (is_directory_we_want_to_list(name, entry_name)) {
            // You can consider using alloca instead.
            char *next = malloc(strlen(name) + strlen(entry_name) + 2);
            sprintf(next, "%s/%s", name, entry_name);
            list(next);
            free(next);
        }
    }

    closedir(dir);
}

from How to recursively list directories in C on LINUX

Okay, my program is running but now i want to save all the file and directory printed to a file like i run my program ./a.out . > buffer where buffer contain what the program should print on the shell

Community
  • 1
  • 1
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32

1 Answers1

1

the line

sprintf(next, "%s/%s", name, entry_name);

could be replaced with

strcpy (next, name);
strcat (next, "/");
strcat (next, entry_name);

and it would do the same thing. Does that clarify it for you?

Jules
  • 14,841
  • 9
  • 83
  • 130
  • that was fast, yes i get it a lot better now thank you, and yes it was sprintf, sorry – Saxtheowl Jul 03 '13 at 17:02
  • 1
    Do note that every call to `strcat()` involves walking the entire string to find the end of it, so a single `sprintf()` call here is much more efficient. – Adam Rosenfield Jul 03 '13 at 17:05