我正在尝试从文本文件中读取单词并将它们添加到链接列表中,但我觉得我的执行错误。下面是插入和读取文件的代码。
Word *insert_at_back(Word *head, Word *new_word) {
if (head == NULL) {
head = new_word;
new_word->next = NULL;
}
else {
while (head != NULL) {
head = head->next;
}
head->next = new_word;
}
return head;
}
Word *read_word_list(const char *filename, Word *head) {
FILE *f = fopen(filename, "rb");
if (f == NULL) {
fprintf(stderr, "Could not open %s.\n", filename);
return head;
}
Word word;
fread(&word, sizeof(Word), 1, f);
while (!feof(f)) {
if (word.string != 0) {
Word *new_word = (Word *)malloc(sizeof(Word));
if (new_word != NULL) {
head = insert_at_back(head,new_word);
}
}
fread(&word, sizeof(Word), 1, f);
}
fclose(f);
return head;
}