来自文件的链接列表

时间:2011-11-24 12:37:27

标签: c linked-list fgets

我正在努力解决C问题,我无法弄清楚我做错了什么。

我正在使用链接列表来存储单词。当我执行以下操作时:

list *myList = list_new();
list_append(myList,"Word_01");
list_append(myList,"Word_02");
list_append(myList,"Word_03");
list_append(myList,"Word_04");
list_print(myList);

一切都很好,我得到了这个输出:

Word_01 -> Word_02 -> Word_03 -> Word_04 -> NULL

好的,现在我从存储在文件中的列表中获取单词:

Word_01
Word_02
Word_03
Word_04

执行此代码:

const char *filename;
filename = "list";
list *myList2 = list_new();
FILE* file = NULL;
size_t size;
char line[256];
file = fopen(filename, "r");
if (file != NULL)
{
    printf("File opened.\n");
    while (fgets(line, 256, file) != NULL) {
        list_append(myList2, line);
    }
    fclose(file);
}
else {
    printf("Could not open file.\n");
    exit(EXIT_FAILURE);
}
list_print(myList2);

然后我得到以下输出:

Word_04 -> Word_04 -> Word_04 -> Word_04 -> NULL

有人能解释我为什么会这样吗?

修改 这是list_append()

void list_append(list *l, char *w) {
    word *new_word = malloc(sizeof(word));
    if (l == NULL || new_word == NULL) {
        exit(EXIT_FAILURE);
    }
    new_word->_word = w;
    new_word->next = NULL;
    if (l->first->_word == "") {
        l->first = new_word;
    }
    else {
        word *temp = malloc(sizeof(word));
        temp = l->first;
        while(temp->next != NULL) {
            temp=temp->next;
        }
        temp->next = new_word;
    }
}

1 个答案:

答案 0 :(得分:1)

如注释所述,您正在错误地处理字符串。 C风格的字符串不是你可以用==等于或者用=分配的东西。这是一个C ++教程,但给出了对C字符串的一个很好的解释:

http://www.learncpp.com/cpp-tutorial/66-c-style-strings/

另请查看strcmp(),strcpy()和strlen()的文档。我使用这些函数修复了注释中注明的位 - 请注意我的注释:

void list_append(list *l, char *w) {
    word *new_word = malloc(sizeof(word));
    if (l == NULL || new_word == NULL) {
        exit(EXIT_FAILURE);
    }

    //new_word->_word = w;
    // Allocate space and copy contents, not the pointer
    new_word->_word = malloc(strlen(w) + 1);
    strcpy(new_word->_word, w);

    new_word->next = NULL;
    //if (l->first->_word == "") {
    // Use strcmp() to compare the strings - returns 0 if they are equal
    if (strcmp(l->first->_word, "") == 0) {
        l->first = new_word;
    }
    else {
        word *temp = malloc(sizeof(word));
        temp = l->first;
        while(temp->next != NULL) {
            temp=temp->next;
        }
    temp->next = new_word;
    }
}
相关问题