从文件读取到链表时遇到问题
Trouble with reading from file to linked list
我正在尝试创建从文本文件中读取 child 的名称并将它们写入链表的函数。我有一个将它写入列表的结构,因为整个列表都充满了文件中的姓氏。
#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++ 关键字。您可能还想从缓冲区中删除尾随换行符以及任何前导或尾随空格。
我正在尝试创建从文本文件中读取 child 的名称并将它们写入链表的函数。我有一个将它写入列表的结构,因为整个列表都充满了文件中的姓氏。
#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++ 关键字。您可能还想从缓冲区中删除尾随换行符以及任何前导或尾随空格。