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

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

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