c - 从文件读取到链表的问题
问题描述
我正在尝试制作从文本文件中读取孩子姓名并将其写入链接列表的函数。我有一个将它写入列表的结构,因为整个列表都填充了文件中的姓氏。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Child child;
struct Child {
char *name;
child *next;
};
void readFromFile(char fileName[], child **head) {
FILE *file;
if (!(file = fopen(fileName, "rt"))) {
printf("Can't open file\n");
abort();
} else {
static char buffer[1024];
while (fgets(buffer, 1024, file)) {
child *new = (child *)malloc(sizeof(child));
new->name = buffer;
new->next = (*head);
(*head) = new;
}
}
fclose(file);
}
void printList(child *head) {
child *tmp = head;
while (tmp) {
printf("%s", tmp->name);
tmp = tmp->next;
}
}
int main() {
child *head = NULL;
readFromFile("file.txt", &head);
printList(head);
return 0;
}
文件包含这种风格的数据:
John
Ann
Adam
Arthur
解决方案
您的阅读循环使所有节点都指向同一个静态数组:
static char buffer[1024];
while (fgets(buffer, 1024, file)) {
child *new = (child *)malloc(sizeof(child));
new->name = buffer;
new->next = (*head);
(*head) = new;
}
您应该为每个节点分配字符串的副本:
char buffer[1024];
while (fgets(buffer, sizeof buffer, file)) {
child *new_node = (child *)malloc(sizeof(child));
new_node->name = strdup(buffer);
new_node->next = *head;
*head = new_node;
}
还建议检查内存分配失败并避免使用 c++ 关键字。您可能还想从缓冲区中删除尾随换行符以及任何前导或尾随空格。
推荐阅读
- flutter - flutter :浮动在容器边距或填充上的文本
- javascript - Unexpected token, expected "," in JSX
- sql - 在 SQL 表中动态存储值
- android - Flutter 在 iOS 设备上出现“连接到服务协议时出错:HttpException ...”错误
- dynamics-crm - 将第三方应用程序与 Dynamics CRM 集成
- c# - windows 安装程序无法访问目录
- google-apps-script - 打开现有的 google 工作表,然后将其内容(包括单元格格式)复制到另一个工作表中
- redux - 动作必须是普通对象。使用自定义中间件进行异步操作 errorfor dispatching actions
- c++ - 如果使用迭代器,如何解决迭代列表的问题?
- laravel - 如何为 X-CSRF-TOKEN 启用生命周期活动状态