【发布时间】:2017-09-15 15:32:23
【问题描述】:
我是否错误地使用了fgets()?
我正在尝试构建一个字符串链接列表 (char *),将每个新行添加到 LL 的末尾。我正在从文件中读取这些行,但由于某种原因,只有在 while 循环内使用 fgets() 时,每一行都会被正在处理的当前行覆盖,但 add 函数似乎正确接收每一行。
如果我在main() 中单独添加行,则没有问题。
这是一个示例输入文件:
input.txt:
This life, which had been the
tomb of his virtue and of his
honour, is but a walking
shadow; a poor player, that
struts and frets his hour upon
the stage, and then is heard
no more: it is a tale told by an
idiot, full of sound and fury,
signifying nothing.
--William Shakespeare
代码:
#include <stdio.h> //printf, fopen
#include <stdlib.h> //exit, EXIT_FAILURE
#include <string.h> //strlen
struct node {
char *line;
struct node *next;
};
void print(struct node *node);
void add(struct node **head, char *newLine) {
//printf("%s", newLine);
struct node *new_node = (struct node *)malloc(sizeof(struct node));
struct node *curr = *head;
new_node->line = newLine;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new_node;
}
print(*head);
}
void print(struct node *node) {
printf("\n");
while (node != NULL) {
printf("%s\n", node->line);
node = node->next;
}
}
int main(int argc, char *argv[16]) {
char newLine[81];
struct node *head = NULL;
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("ERROR: file open failed");
exit(EXIT_FAILURE);
}
while (fgets(newLine, 81, fp)) {
add(&head, newLine);
}
add(&head, "why");
add(&head, "does");
add(&head, "this");
add(&head, "work??");
fclose(fp);
print(head);
return 0;
}
有人可以向我解释发生了什么吗?我已经用头撞墙太久了。我已经尝试使用一些注释打印语句,但未能成功调试。
【问题讨论】:
-
拿些纸。跟踪对
add的调用并绘制您的链接列表的表示。特别注意'node->line'指向什么。 -
这种行为有好几千个;(
标签: c linked-list fgets