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



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

以下 while 循环

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-loop 中的"字符串"变量在每次迭代后插入链表时都不会改变?它只是插入第一行四次。

我错过了什么?

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

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

插入代码不正确。 需要先malloc(),然后将字符串strcpynode的数据中。在这里,您只是在复制指针。

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

相关内容

  • 没有找到相关文章

最新更新