【问题标题】:Using fgets() to read file line by line in C使用 fgets() 在 C 中逐行读取文件
【发布时间】:2014-09-16 14:36:33
【问题描述】:

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

下面的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循环中的“字符串”变量在每次迭代后插入到链表中时都不会改变?它只是将第一行插入四次。

我错过了什么?

UPDATE:我的插入代码如下:

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

【问题讨论】:

  • 问题很可能出在你的链表代码上,而不是文件读取代码上,所以你需要告诉我们。
  • 可以添加插入代码吗?
  • 您的 insert() 需要复制传递给它的字符串,因为该字符串将在循环的下一次迭代中被覆盖。
  • 使用类似insert(file_list, strdup(string));
  • 我无法理解这样的心态,当面对“标准功能不按文档工作”与“自己的代码错误”的选项时,实际上怀疑标准功能......;)

标签: c file linked-list fgets


【解决方案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;
    }  
}

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多