Push contents of directory into Array As a String C

I have literally zero(less than 2 days total) experience in C programming and my OS course is expecting us to code in C. I am wanting to recursively add all of the files in a directory to an array so I can sort and output to Console. I have figured out how to Print all of the names but I cannot figure out how to push them into an Array. I have attached my code for printing all of the folders and directories. How would I instead of printing to console, store these values in an array?

void dirSearch(const char *name, int level)
    DIR *dir;
    struct dirent *ent;

    if (!(dir = opendir(name)))
    if (!(ent = readdir(dir)))

    do {
        if (ent->d_type == DT_DIR) {

            int len = snprintf(path, sizeof(path)-1, "%s/%s", name, ent->d_name);
            path[len] = 0;
            if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
            printf("%*s %s\n", level*2, "", ent->d_name);
            dirSearch(path, level + 1);
            printf("%*s- %s\n", level*2, "", ent->d_name);
    } while(ent = readdir(dir));


  • Put these before while loop:

    char *array[size];
    int i = 0;

    Substitute size with reasonably big number to fit all stuff in array. i is your index where to put each element. Put this instead or alongside your printf:

    array[i] = ent->d_name;
    i++; //advance the index

    You will need another loop like for (int i = 0; i < sizeof(array); i++) to get the values out of the array.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion