gpt4 book ai didi

从文本文件创建链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:34:56 24 4
gpt4 key购买 nike

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

文本文件的一个例子是:

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

}

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

最佳答案

好的,为此您需要先分配一个节点条目,然后将您刚刚读取的行复制到其中。然后将其添加到列表中。 (我省略了错误处理,例如 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;
}

关于从文本文件创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com