C语言中的链表(从文件中读取)

6

我很新于C语言编程,遇到了一些困难。我的目标是从文本文件中逐行读取内容,并将每行添加到一个简单链表中。我已经尝试了很多,但都没有找到解决方法。到目前为止,我能够从文件中读取数据,但是我不知道如何逐行保存并将其添加到链表中。

以下是我目前的代码:

struct list {
char string;
struct list *next;
};

typedef struct list LIST;

int main(void) {

    FILE *fp;
    char tmp[100];
    LIST *current, *head;
    char c;
    int i = 0;
    current = NULL;
    head = NULL;
    fp = fopen("test.txt", "r");

    if (fp == NULL) {
        printf("Error while opening file.\n");
        exit(EXIT_FAILURE);
    }

    printf("File opened.\n");

    while(EOF != (c = fgetc(fp))) {
       printf("%c", c);
    }

    if(fclose(fp) == EOF) {
        printf("\nError while closing file!");
        exit(EXIT_FAILURE);
    }
    printf("\nFile closed.");
}

如果有人能给我一些提示,告诉我下一步该做什么才能让它起作用,我会非常感激。我习惯于使用Java,但在C语言上面就不太能理解如何去做这些事情了。

5
char string; 是一个一字节的变量。它只能存储8位数据,不能存储任何类型的文本字符串。可能你想要使用 char *string;。也许你可以尝试使用 strdup() 在读取每个字符串时创建其副本,并将返回值分配给每个链接的 string 元素。阅读这篇文章可能会有所帮助。 - r3mainer
1个回答

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

struct list {
    char *string;
    struct list *next;
};

typedef struct list LIST;

int main(void) {
    FILE *fp;
    char line[128];
    LIST *current, *head;

    head = current = NULL;
    fp = fopen("test.txt", "r");

    while(fgets(line, sizeof(line), fp)){
        LIST *node = malloc(sizeof(LIST));
        node->string = strdup(line);//note : strdup is not standard function
        node->next =NULL;

        if(head == NULL){
            current = head = node;
        } else {
            current = current->next = node;
        }
    }
    fclose(fp);
    //test print
    for(current = head; current ; current=current->next){
        printf("%s", current->string);
    }
    //need free for each node
    return 0;
}

当您不释放每个节点时会发生什么? - RoadRunner
1
现代操作系统会在程序结束时释放已分配的内存。因此,不会发生任何特别的事情。也许是这样的:-) - BLUEPIXY
为了避免“分段错误”(segmentation fault)的错误,需要指定字符串的大小: 结构体列表 { char 字符串[128]; 结构体列表 *下一个; }; - Vitalii Blagodir
那是错误的建议。应该检查返回值而不是这样做。 - BLUEPIXY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接