我使用fgets()
不正确?
我想建立一个字符串的链表( char *
添加每个新行LL的结束)。 我读从一个文件中的这些线路,但由于某种原因,每行获取当前行覆盖正在处理中,只使用时fgets()
内while
循环,但附加功能似乎被正确接收的每一行。
如果我单独添加行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;
}
可能有人请向我解释发生了什么? 我一直在敲打我的头靠在墙上太久。 目前已经有一些评论打印语句我一直在尝试使用,未成功进行调试。