【发布时间】:2011-02-01 17:11:38
【问题描述】:
我正在尝试读取文本文件并将每一行存储在 void* 类型的链接列表的节点中。 这是列表的头文件。
#ifndef LINKEDL
#define LINKEDL
struct node_s {
void *data;
struct node_s *next;
};
struct node_s *node_create(void*);
struct node_s *list_insert_after(struct node_s*, void*);
struct node_s *list_insert_beginning(struct node_s*, void*);
int list_remove(struct node_s*, struct node_s*);
int list_foreach(struct node_s*, int(*)(void*));
int printstring(void *s);
#endif
所有的链表函数都经过了彻底的测试,所以我想问题在于我如何使用它。我想要实现的是每个节点都有一行,而我现在拥有的是每个节点的最后一行。我想这与 char 指针有关,但已经花了两个小时没有取得惊人的突破,所以也许有人可以帮忙? 此外,我使用的列表是修改后的列表,如 here 所示。
if (file == NULL)
{
perror("Error opening file");
}
else
{
char mystring[SIZE];
char temp[SIZE];
list = node_create((void*)mystring);
current = list;
while (fgets(mystring, SIZE, file) != NULL)
{
strcpy(temp, mystring);
printf("%d\t%s",counter++,temp);
current=list_insert_after(current, (void*)temp);
}
fclose(file);
}
更新: 谢谢大家。
【问题讨论】:
-
你只有一个字符串变量(mystring),所以你所有的节点都指向同一个字符串。您需要为要指向的每个新节点分配一个新字符串。
标签: c gcc linked-list