【发布时间】:2014-11-05 21:12:17
【问题描述】:
我最近开始学习 C 编程。我有一些java经验,所以我知道我的代码方式,我喜欢思考.. 我正在做的这件小事正在杀死我。 我正在尝试制作一个从文本文件中读取行的程序->将其存储在单链表中->打印出单链表 到目前为止,这是我的代码:
typedef struct node {
char *data;
struct node *next;
} node;
node *start = NULL;
node *current;
void add(char *line) {
node *temp = malloc(sizeof(node));
// This line under I believe where my problem is...
temp->data = line;
temp->next = NULL;
current = start;
if(start == NULL) {
start = temp;
} else {
while(current->next != NULL) {
current = current->next;
}
current->next = temp;
}
}
这是我读取文件并将字符发送到添加函数的函数
void readfile(char *filename) {
FILE *file = fopen(filename, "r");
if(file == NULL) {
exit(1);
}
char buffer[512];
while(fgets(buffer, sizeof(buffer), file) != NULL) {
// I've tried to just send i.e: "abc" to the add function
// which makes the program work.
// like: add("abc");
// my display method prints out abc, but when I'm sending buffer
// it prints out nothing
// Thing is, I've spent way to much time trying to figure out what
// I'm doing wrong here...
add(buffer);
}
fclose(file);
}
我确信这是一个相当简单的问题,但我在这个问题上花了太多时间。 如果还有其他看起来不合适/可能更好的东西,我也很感谢您的反馈:)
【问题讨论】:
标签: c file singly-linked-list