C从文本文件插入链接列表

时间:2017-11-25 14:45:49

标签: c file linked-list

我正在尝试从文本文件中读取单词并将它们添加到链接列表中,但我觉得我的执行错误。下面是插入和读取文件的代码。

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;
}

0 个答案:

没有答案