c - 在c中将文本文件逐行保存到链表中

标签 c linked-list file-handling

我需要将一个文本文件逐行保存到链表中,然后显示保存的元素。 这是我尝试过的:

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

typedef struct node 
{
    char data;
    struct node *next;
}Element, *List;

List init(void);

int main (){

    List current, head, newnode;
    FILE *f = fopen("text.txt", "r");
    head = current = NULL;

    while (getc(f) != EOF){
        newnode = malloc(sizeof(Element));
        fgets(&newnode -> data, sizeof(newnode), f);
        newnode -> next = NULL;

        if(head == NULL){
            head = current = newnode;
        }
        else{
            current -> next = newnode;
            current = newnode;
        }

    }

    current = head;

    while(current != NULL){
        printf("%s", &current -> data);
        current = current -> next;
    }

    fclose(f);
    return 0;
}

文本是:

I stand amid the roar
Of a surf-tormented shore
And I hold within my hand
Grains of the golden sand
How few! yet how they creep
Through my fingers to the deep
While I weep while I weep
O God can I not grasp
Them with a tighter clasp
O God can I not save
One from the pitiless wave
Is all that we see or seem
But a dream within a dream

但到目前为止我得到的是:

 stnd midtheroa
f asur-tomened hor
nd  hod wthi myhan
rais o th godensan
ow ew!yethowthe crep
hrogh y fnges t th dep
hil I eepwhie Iwee
 Go ca I ot ras
hemwit a igher las
 Go ca I ot aveOnefro th piiles wve
s al tat e se o sem
ut  dram ithn adrem

它会跳过一些字符,我认为原因是 fgets 每次读取一定数量的字符。但我找不到解决方案使其成为应有的样子,而且我还不太熟悉链表概念。 我将非常感谢任何帮助和建议,以使其发挥作用并将坡先生从这种废话中拯救出来。 PS:应该使用C90来完成,所以有些功能被禁用。

最佳答案

来自评论的注释:getc从输入流中读取一个字符。您需要以其他方式检查输入流是否位于文件末尾。

您正在使用单个char而不是 char 的数组s。使用char data[51]; , fgets(newnode->data, sizeof(newnode->data), f); ,和printf("%s", current->data);

关于c - 在c中将文本文件逐行保存到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59864789/

相关文章:

c - 阅读命名管道问题

c++ - C 是否有任何 setfill() 替代方案?

c - 尝试通过链表读取数组时得到错误的整数

C - 链表插入

android - 在 Android 中将 Assets 或原始或资源文件作为 File 对象读取

android - 将 Arraylist 保存到文件 android

arrays - 在 CSV 中写入数组值

c - 获取由 mkstemp() 创建的文件名

sql - 如何在不遍历SQLite3的情况下从SQL表中获取最后一列的名称?

c - 本链表程序回顾