问题
The following code allows me to read a directory recursively and print all the files and their paths in a struct variable using linked lists. The problem I'm having is within the function when I print out the full path it shows it correctly but in the main when I was read through the linked lists, the fullpaths show up as null. Where am I going wrong?
Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
const char *path_format = "%s/%s";
typedef struct search search;
struct search {
char *path;
char *fileName;
char *fullPathToFile;
search *next;
};
// Modified to take a node ptr. This should be the last node in the list
// Returns a node ptr. This is the new last node in the list
search * show_dir_content(char * path, search *node) {
DIR * d = opendir(path);
if(d==NULL) return node;
struct dirent * dir;
while ((dir = readdir(d)) != NULL) {
if(dir-> d_type != DT_DIR) {
// Found a file. Alloc a new search node and fill in
search *new_node = malloc(sizeof(search));
char f_path[512];
sprintf(f_path, path_format, path, dir->d_name);
printf("%s\n",f_path);
new_node->fullPathToFile = f_path;
new_node->fileName = dir->d_name;
new_node->path = path;
new_node->next = NULL;
// Append to end of list
node->next = new_node;
// Update node pointer to now point to the new node
node = node->next;
}
else
// if it is a directory
if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {
char d_path[512];
sprintf(d_path, path_format, path, dir->d_name);
node = show_dir_content(d_path, node);
}
}
closedir(d);
// Return the last node (this may be same as input parameter if no files found
return node;
}
int main(int argc, char **argv) {
search root = {0};
show_dir_content(argv[1], &root); // Note that root is a dummy node.
// The list actually begins at root->next
// Also, before you exit, free all mem
search *node = root.next, *next, *clr;
while (NULL != node) {
//printf("f_path : \t%s\n", node->fullPathToFile);
next = node->next;
node = next;
}
while (NULL != node) {
free(node->path);
free(node->fileName);
free(node->fullPathToFile);
clr = node->next;
free(node);
node = next;
}
return(0);
}
Printing the fullpath within the function seems to work well with printf("%s\n",f_path); but when I try to store f_path into my new_node->fullPathToFile and then try printing it in the main it doesn't go as I had hoped. You can try uncommenting printf("f_path : \t%s\n", node->fullPathToFile); to understand what I mean.
Any help is appreciated.
来源:https://stackoverflow.com/questions/41855178/recursive-function-linked-lists-sprintf-not-saving-variable-into-struct-varia