【问题标题】:Trouble with reading from file to linked list从文件读取到链表的问题
【发布时间】:2019-09-22 23:21:12
【问题描述】:

我正在尝试制作从文本文件中读取孩子姓名并将其写入链接列表的函数。我有一个将其写入列表的结构,因为整个列表都填充了文件中的姓氏。

#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

【问题讨论】:

  • 你正在覆盖buffer
  • 注意"rt"不是标准兼容模式,必须是"r""rt" 是微软的垃圾。
  • new-&gt;name = strdup(buffer);(然后你当然需要free每个name
  • printf("Can't open file\n"); 是无用错误消息的典型示例。 perror(fileName)。打印一个错误,其中包括路径和打开失败的原因,并将这些内容打印到正确的流中。

标签: c linked-list file-read


【解决方案1】:

您的阅读循环使所有节点都指向同一个静态数组:

    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++ 关键字。您可能还想从缓冲区中去除尾随换行符以及任何前导或尾随空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-17
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多