如何从文本文件中读取具有可变长度的单词并将它们添加到C中的列表中

时间:2017-04-28 14:52:44

标签: c list file pointers singly-linked-list

我必须创建一个函数,在输入中接收文件的名称,该文件包含随意顺序的单词,并且必须返回指向列表的指针,其中每个节点都包含指向每个单词的指针。我该怎么办?

typedef struct _NODE {
char* word;
struct _NODE *next;
} NODE;

我试图实现这个

NODE* createFromFile(char* nameFile)
{
    FILE* ptr = fopen(nameFile, "r");
    if (ptr == NULL)
    {
        return NULL;
    }
    NODE* n = NULL;
    NODE* temp= n;

    while (!feof(ptr))
    {
        char store[MAX_WORD];
        NODE* new = NULL;

        new = (NODE*)malloc(sizeof(NODE));
        new->word=fgets(store, MAX_WORD, ptr);
        new->next = NULL;

        if (n == NULL)
        {
            n = new;
            temp = n;
        }
        else
        {
             while (temp->next != NULL)
                temp = temp->next;

             temp->next = new;
        }
    }
    fclose(ptr);
    return n;
}

但是如果我实现后面的函数来打印它,它会打印随机字符:

void printDictionary(NODO* dictionary)
{
    NODO* temp = dictionary;

    while (temp != NULL)
    {
        printf("\"%s\"\n", temp->word);
        temp = temp->next;
    }
}

请帮助

0 个答案:

没有答案