以下代码允许我以递归方式读取目录,并使用链接列表在struct变量中打印所有文件及其路径。 当我打印出正确显示它的完整路径时,我遇到的问题是在函数内,但是当我通过链接列表读取时,完整路径显示为null。 我哪里错了?
代码:
#include #include #include #include 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("%sn",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%sn", 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); }
在函数中打印完整路径似乎与printf("%sn",f_path);
但是当我尝试将f_path
存储到我的new_node->fullPathToFile
然后尝试在main中打印它时它并没有像我希望的那样。 您可以尝试取消注释printf("f_path : t%sn", node->fullPathToFile);
明白我的意思。
任何帮助表示赞赏。
以上就是c/c++开发分享递归函数+链表。 sprintf没有将变量保存到struct变量中。相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/522278.html