[英]Append a string from fscanf to linked list in C
我想读取一个文件并将每个单词放在一个链表中。 当我读取文件时,链表具有良好的节点数,但所有节点都等于最后一个字。
例如,如果我的文本文件是:
Hello good sir
我的链表如下所示:
[sir,sir,sir]
应该是这样的:
[Hello, good, sir]
我的主要
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct NodeTag {
char *data;
struct NodeTag *next;
} Node;
Node *Node_create();
typedef struct ListTag {
struct NodeTag *first;
} List;
List *List_create();
void List_append(List *list, char *str);
void List_print(List *list);
int main(void) {
char word[100];
FILE *file = fopen("file.txt", "r");
if(file == NULL) {
printf("error in opening file\n");
return 1;
}
List *l = List_create();
while(fscanf(file, "%s", word) == 1){
List_append(l, word);
}
return 0;
}
这是我的功能。 我删除了destroy和free函数以使其更清晰。
Node *Node_create() {
Node *node = malloc(sizeof(Node));
assert(node != NULL);
node->data = "";
node->next = NULL;
return node;
}
List *List_create() {
List *list = malloc(sizeof(List));
assert(list != NULL);
Node *node = Node_create();
list->first = node;
return list;
}
void List_append(List *list, char *str) {
assert(list != NULL);
assert(str != NULL);
Node *node = list->first;
while (node->next != NULL) {
node = node->next;
}
node->data = str;
node->next = Node_create();
}
void List_print(List *list) {
assert(list != NULL);
printf("[");
Node *node = list->first;
while (node->next != NULL) {
printf("%s", node->data);
node = node->next;
if (node->next != NULL) {
printf(", ");
}
}
printf("]\n");
}
如果我做这样的事情,它将正常工作。 所以我想我只附加了单词的指针,所以它一次又一次地指向同一个地方?
List_append(l, "test1");
List_append(l, "test2");
输出:
[test1, test2]
请注意,在main
,您有一个存储字符串的缓冲区:
char word[100];
您将word
作为参数传递给List_append
方法,在此期间您可以编写
node->data = str;
这意味着所有节点都指向main
的word
缓冲区作为字符串,因此所有节点都将显示相同的字符串。
要解决此问题,您需要在某处复制缓冲区。 我建议做这样的事情:
node->data = strdup(str);
代码中可能还有其他问题,但在您继续之前,这肯定是您需要解决的问题。 尝试更新此问题,看看它是否可以解决您的问题。 正如@Sean Bright指出的那样,当你进行追加时,似乎你也会覆盖错误的字符串指针,所以你可能也需要修复它。
希望这可以帮助!
在List_append
里面,你这样做:
node->data = str;
这样可以保存指向以str
传递的数据的指针。 你在main中调用List_append(l, word)
,这意味着你每次都传递相同的内存,所以每个列表成员都指向同一块内存。
您需要在List_append
执行此List_append
:
node->data = strdup(str);
这会将字符串复制到新分配的缓冲区中。 请务必在清理时将其free
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.