c链表从txt文件读取

标签 c linked-list

我是 c 语言的新手,想制作一个可以从 txt 文件中读取链表的程序。例如,我的文件是这样的

0 1 6 4 8 6 8 15 56 4 864 68

我想阅读信息,然后尝试将其显示给用户。 这就是我所做的。这给了我错误,它在我声明的主要部分写入它之前的 head 预期表达式。

A = readList(head); 
printList(head);

我的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct linkedList{
    int value;
    struct linkedList *next;
} linkedList, head;

linkedList *readList(linkedList *head)
{
    FILE *dataFile;
    dataFile = fopen("duom.txt", "r");
    if(dataFile == NULL) {
        printf("Nepasisekė atidaryti failo\n");
    } else {
        printf("Duomenų failą pavyko atidaryti\n");
    }
    while (!feof (dataFile))
        if (head == NULL) {
            head = malloc(sizeof(linkedList));
            fscanf(dataFile, "%d", &head -> value);
            head -> next = NULL;
        } else {
            struct linkedList *current = head;
            struct linkedList *temp = malloc(sizeof(linkedList));
            while(current -> next != NULL) {
                current = current -> next;
            }
            fscanf(dataFile, "%d", &temp -> value);
            current -> next = temp;
            temp -> next = NULL;
        }
    return head;
}
void printList(linkedList *head)
{
    linkedList *current = head;
    while (current != NULL) {
        printf("%d->", current -> value);
        current = current -> next;
    }
    printf("NULL\n");
    return;
}
int main()
{
    linkedList A;
    A=readList(head);
    printList(head);
    return 0;
}

最佳答案

您正在为 readList 中的 head 分配空间,但您正在那里传递一些不存在的参数(readList(head) 和 printList(head))。你可以做些什么来解决你的问题: 将您的主要更改为:

int main()
{
    linkedList *A = NULL; /* creating pointer to your linked list. */
    A=readList(A);  /* Read linked list from file (And allocate it if it's not allocated */
    printList(A); /* print list */
    return 0;
}

如果您希望 A 全局可访问,只需将指针 A 的声明移到 main 之外。

关于c链表从txt文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227292/

相关文章:

c - 有没有一种快速的方法可以在字符串之间插入一个字符?

c - 是否可以对字符数组进行位掩码

c - 确保链接列表已释放

java - 如何根据字符串java中的一个单词对链接列表进行排序

c - C 中字节大小的位模式及其相关性?

c - C中如何确定字符串数组的长度

c - 为什么这段用于反向打印单向链表的代码段没有按预期工作?

java - 从 String 表示中加载 Java 中的列表?

c - 带链表的哈希表

java - 如何获取从最后一个元素开始的前向迭代器