0
typedef struct file{/*This is the struct to add*/
    char* fileNames;
}File;
File* scanDir(char *path,File file[],int i){/*Func works recursively*/
    DIR *dir;

    struct dirent *dp;

    char * file_name;
    dir = opendir(path);
    if(dir==NULL)
        return file;
    chdir(path);
    while ((dp=readdir(dir)) != NULL) {
        if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")){}
        else {
            file_name = dp->d_name; /*use it*/
            printf("file_name: \"%s\"\n",file_name);
            file[i]=create(file_name,file[i]);/*This create function adds the file name into the file struct*/
            i++;
            scanDir(dp->d_name,file,i);

        }
    }
    chdir("..");
    closedir(dir);
    return file;
}

I am trying to add file names to struct array. int i counts the array order. How can I read the files by adding to struct array?

fulladder
  • 1
  • 3
  • 1
    `i++; scanDir(dp->d_name, file, i);` - this can't possibly work. It will overwrite the results of the recursive call in the next iteration of the main loop, as you use the same value of `i` in the recursive call and in the next iteration. You should make `i` an `int *` to keep track of the current cursor position across recursive calls, or make it a global, or have scanDir() return the new cursor offset. Also, the recursive call should be conditional on `dp->d_name` being a directory. Hint: look at `stat(2)` to determine if a `dirent` is a directory. – Filipe Gonçalves Dec 28 '16 at 00:37
  • 1
    this seems to be a duplicate of and and – user3629249 Dec 28 '16 at 18:44

0 Answers0