使用fgets()在C中逐行读取文件

时间:2014-09-16 14:36:33

标签: c file linked-list fgets

所以,我正在努力让我的程序逐行读取文件,将每一行(作为“字符串”)存储到链表中。

以下while-loop

FILE *f;
char string[longest];
while(fgets (string, longest, f) != NULL) {    //Reading the file, line by line
    printf("-%s", string);    //Printing out each line
    insert(file_list, string);  //Why does it not change?
}

printf() - 函数按预期工作,打印出每一行。我把连字符作为测试,看看它是否会在线之间分开。 但是,将“字符串”插入链表时,只会多次插入第一个字符串。

例如,让我们说我有一个文本:

Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.

现在,当读取此文件并打印出结果时,我得到:

-Roses are red,
-Violets are blue,
-Sugar is sweet,
-And so are you.

但是,当打印输出链接列表时,我得到的结果不是得到相同的结果:

Roses are red,
Roses are red,
Roses are red,
Roses are red,

有人知道为什么while循环中的“string”变量在每次迭代后都不会在插入链表时发生变化吗?它只插入第一行四次。

我错过了什么?

更新:我的插入代码如下:

void insert(node_lin *head, char *dataEntry) {
    node_lin * current = head;

    if(current->data == NULL) {
        current->data= dataEntry;
        current->next = NULL;
    }

    else {
        while(current->next != NULL) {
            current = current->next;
        }

        current->next = malloc(sizeof(node_lin));
        current->next->data = dataEntry;
        current->next->next = NULL;
    }
}

1 个答案:

答案 0 :(得分:1)

插入代码并不正确。首先需要malloc()并将strcpy字符串转换为node的数据。在这里你只是复制指针。

void insert(node_lin *head, char *dataEntry) {
    node_lin * current = malloc(sizeof(node_lin));
    node_lin *p = NULL;

    /*make sure that an empty list has head = NULL */
    if(head == NULL) { /*insert at head*/
        strcpy(current->data, dataEntry);
        current->next = NULL;
        head = current;
    } else {
        p = head;
        while(p->next != NULL) {
            p = p->next;
        }
        /*insert at tail*/
        p->next = current;
        strcpy(current->data, dataEntry);
        current->next = NULL;
    }  
}