Howdy, Stranger!

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

Categories

Push contents of directory into Array As a String C

Ron MillerRon Miller Member Posts: 1

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)))
        return;
    if (!(ent = readdir(dir)))
        return;

    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)
                continue;
            getSize(name);
            printf("%*s %s\n", level*2, "", ent->d_name);
            dirSearch(path, level + 1);
        }
        else
            getSize(name);
            printf("%*s- %s\n", level*2, "", ent->d_name);
    } while(ent = readdir(dir));
    closedir(dir);
}

Comments

  • B00B00 Member Posts: 86 ✭✭✭

    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.