从文本文件创建链接列表

时间:2012-12-01 23:16:03

标签: c algorithm text linked-list

我正在自学链接列表并提出了一个需要解决的基本问题。我想逐行读取一个文本文件,该文件将具有名称并将每个名称添加到我的链接列表中。

文本文件的一个例子是:

John
Jacob
Jingleheimer
Smith

我无法弄清楚如何动态添加到我建议的链表中。这是我到目前为止所拥有的。

#include <stdio.h>
#include <stdlib.h>



int main(void)
{
    struct node {
        char *name;
        struct node* next;
    };


    static const char* fileName = "test.txt";
    FILE *fp = fopen(fileName,"r");
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    struct node* head = NULL; // first node

    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1)
    {
        //add line of text to linked list
    }
    if (line)
        free(line);

       exit(EXIT_SUCCESS);

}

任何指向正确方向的指针都会有所帮助。

2 个答案:

答案 0 :(得分:3)

好的,要执行此操作,您需要先分配一个节点条目,然后将刚刚读入的行复制到其中。然后将其添加到列表中。 (我省略了错误处理,例如malloc返回NULL)。

/* This will store the last read line first */
while ((read = getline(&line, &len, fp)) != -1)
{
    struct node *n = malloc(sizeof(*n));
    n->name = strdup(line); /* copy the line since it can get reused by getline */
    n->next = head;
    head = n;
}

答案 1 :(得分:0)

分配内存以保存字符串,将memory =设置为字符串。 然后

node *next = malloc(sizeof(node));
next->name = name;
next->next = NULL;
head->next = next;
head = next;
相关问题