c中的链接列表(从文件中读取)

时间:2014-09-09 13:43:55

标签: c file-io linked-list

我对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中做这些事情。

1 个答案:

答案 0 :(得分:2)

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