I'm working to create a function that takes in a path and reads all the files within it and creates a linked lists. Reading the directory works well but I'm having difficulty creating and storing the relevant information in a linked list for use later.
Heres the structure I'm using currently:
typedef struct searchPool searchPool;
struct searchPool{
char * path;
char * fileName;
char *pathFile;
searchPool * next;
};
The function to create a new element of the type 'SearchPool' is defined as such:
searchPool * mallocStructPool (char * path, char * fileName, char * filePath ) {
searchPool * element = (searchPool*)malloc(sizeof(searchPool));
element->path = malloc(sizeof(char * ));
element->fileName = malloc(sizeof(char * ));
element->pathFile = malloc(sizeof(char * ));
element->path = path;
element->fileName = fileName;
element->pathFile = filePath;
element->next = NULL;
return element;
}
Finally the recursive function that take the list's head is written as such (code commented if you scroll to the right):
void listDir(char * path, searchPool * head){
DIR * d = opendir(path); // open the path
searchPool * element; // create new Element of type SearchPool
struct dirent * dir; // for the directory entries
while ((dir = readdir(d)) != NULL) { // if we were able to read somehting from the directory
if(dir-> d_type != DT_DIR) { // if the type is not directory just print it with blue
char * s = malloc(sizeof(char*)+1); // variable to concatenate
s = concat(path, dir->d_name); // concatenate path and filename together
//printf("%s\n",s);
element = mallocStructPool(dir->d_name, path, s); // malloc new element and set variables
head->next = element;
element->next = NULL;
free(s);
} else
if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {// if it is a directory
char d_path[255]; // here I am using sprintf which is safer than strcat
sprintf(d_path, "%s/%s", path, dir->d_name);
listDir(d_path, element); // recall with the new path
}
}
closedir(d); // finally close the directory
}
The problem is that when the function listDir() is called it only ends up printing the first path that I give it in it's parameters and the rest is ignored. Do I have to return the new element in listDir() after each run? I don't see where I'm going wrong.
Any help is appreciated. Thanks for your time.