递归函数+链表。 sprintf没有将变量保存到struct变量中。

时间:2017-01-25 15:18:23

标签: c recursion linked-list filesystems

以下代码允许我以递归方式读取目录,并使用链接列表在struct变量中打印所有文件及其路径。当我打印出正确显示它的完整路径时,我遇到的问题是在函数内,但在主要读取链表时,完整路径显示为null。我哪里错了?

代码:

#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);
}

打印函数中的完整路径似乎与printf("%s\n",f_path);一起使用,但是当我尝试将f_path存储到我的new_node->fullPathToFile中,然后尝试将其打印在主要版本中时,它并不是printf("f_path : \t%s\n", node->fullPathToFile);。按照我的希望去。您可以尝试取消注释initdb -U dimid 以了解我的意思。

感谢任何帮助。

0 个答案:

没有答案