gpt4 book ai didi

c - C语言中使用fgets()逐行读取文件

转载 作者:行者123 更新时间:2023-11-30 15:30:02 24 4
gpt4 key购买 nike

因此,我正在努力让我的程序逐行读取文件,并将每一行(作为“字符串”)存储到链接列表中。

下面的 while 循环

FILE *f;
char string[longest];
while(fgets (string, longest, f) != NULL) { //Reading the file, line by line
printf("-%s", string); //Printing out each line
insert(file_list, string); //Why does it not change?
}

printf() 函数按预期工作,打印出每一行。我用连字符作为测试,看看它是否会在行之间分开。但是,当将“字符串”插入链表时,只会多次插入第一个字符串。

例如,假设我有一条文本:

Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.

现在,当读取这个文件并打印出结果时,我得到:

-Roses are red,
-Violets are blue,
-Sugar is sweet,
-And so are you.

但是,当打印链接列表时,我没有得到相同的结果,而是得到:

Roses are red,
Roses are red,
Roses are red,
Roses are red,

有谁知道为什么 while 循环中的“string”变量在将其插入链表时每次迭代后都不会改变?它只插入第一行四次。

我错过了什么?

更新:我的插入代码如下:

void insert(node_lin *head, char *dataEntry) {
node_lin * current = head;

if(current->data == NULL) {
current->data= dataEntry;
current->next = NULL;
}

else {
while(current->next != NULL) {
current = current->next;
}

current->next = malloc(sizeof(node_lin));
current->next->data = dataEntry;
current->next->next = NULL;
}
}

最佳答案

插入代码不正确。需要首先使用malloc()并将字符串strcpy写入node的数据中。这里您只是复制指针。

void insert(node_lin *head, char *dataEntry) {
node_lin * current = malloc(sizeof(node_lin));
node_lin *p = NULL;

/*make sure that an empty list has head = NULL */
if(head == NULL) { /*insert at head*/
strcpy(current->data, dataEntry);
current->next = NULL;
head = current;
} else {
p = head;
while(p->next != NULL) {
p = p->next;
}
/*insert at tail*/
p->next = current;
strcpy(current->data, dataEntry);
current->next = NULL;
}
}

关于c - C语言中使用fgets()逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com