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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25746255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:21:03  来源:igfitidea点击:

Linked list in c (read from file)

cfile-iolinked-list

提问by user16655

I'm very new to C-programming, and I'm having some difficulties. I'm trying to read line from line to a text file, and then add each line to a simple linked list. I have tried a lot, but I haven't found a solution. So far in my code I'm able to read from the file, but I can't understand how to save the text line for line and add it to the linked list.

我对 C 编程很陌生,我遇到了一些困难。我正在尝试从一行读取一行到一个文本文件,然后将每一行添加到一个简单的链表中。我已经尝试了很多,但我还没有找到解决方案。到目前为止,在我的代码中,我能够从文件中读取,但我无法理解如何保存文本行并将其添加到链接列表中。

This is what I have so far:

这是我到目前为止:

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.");
}

If anyone could give me some pointers on what I need to do next to make it work, I would highly appreciate it. I'm used to Java, and somehow my brain can't understand how to do these things in C.

如果有人能给我一些关于我接下来需要做什么才能使它工作的指示,我将不胜感激。我习惯了 Java,不知何故,我的大脑无法理解如何用 C 来做这些事情。

采纳答案by BLUEPIXY

#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;
}