我需要将一个文本文件逐行保存到链表中,然后显示保存的元素。 这是我尝试过的:
#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", ¤t -> 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/