I'm working with a linked list to get a list of all files from a directory recursively.
But for some reason I can not walk through the list to print the name of all nodes.
The output of the line printf("%s\n", p->name);
is just garbage. At compilation there are also two warnings. I marked the lines with a comment in the code below.
Here's the code:
typedef struct {
char *name;
struct FileList *next;
} FileList;
FileList *head = NULL;
FileList *cur = NULL;
long int totalSize = 0;
FileList* appendToFileList(char *name) {
FileList *ptr = (FileList*) malloc(sizeof(FileList));
if (ptr != NULL) {
ptr->name = name;
ptr->next = NULL;
if (head == NULL) { //if its the first value add it to the head node
head = cur = ptr;
printf("added value to head %s\n", head->name); //this statement works correctly
} else {
cur->next = ptr; //warning "warning: assignment from incompatible pointer type" here
cur = ptr;
printf("added value %s\n", cur->name); //this statement works correctly
}
} else {
return NULL;
}
return ptr;
}
int ftwCallback(char *file, struct stat *info, int flag) {
if(flag == FTW_F) { //if entry is a file
appendToFileList(file);
totalSize += info->st_size;
}
return 0;
}
int main(int argc, char **argv) {
//this function walks a given directory recursively and calls "ftwcallback" for each entry
ftw(argv[1], ftwCallback, getdtablesize() - 1);
FileList *p = head;
while (p->next != NULL) {
printf("%s\n", p->name); //just garbage here
p = p->next; //warning "warning: assignment from incompatible pointer type" here
}
printf("Total size: %d\n", totalSize);
return 0;
}
I adopted a bit of the code from this example.
What's going wrong here?