【问题标题】:How to read line by line a txt file using fgets in C如何在C中使用fgets逐行读取txt文件
【发布时间】:2021-09-13 11:07:36
【问题描述】:

我正在用 C 语言创建一个 GIF 制作程序。在文件管理的一部分中,我将一个 .txt 文件加载到一个链接列表中。我想使用 fgets 逐行加载,但由于某种原因,我的程序陷入了无限循环。这是我写的代码:

/*
Use: create a linked list from the .csv files and return it's head
Input: None
Output: head
*/
FrameNode* loadProject()
{
    FrameNode* head = NULL;
    FrameNode* curr = NULL;
    FrameNode* newNode = NULL;

    FILE* project = NULL;
    char* path = NULL;
    char line[BUFF_SIZE] = { 0 }; 

    printf("Enter the path of the project (including project name):\n");
    path = myFgets();

    project = fopen(path, "r");

    if (project)
    {
        // create the list head
        fgets(line, BUFF_SIZE, project);
        head = loadNode(line);
        curr = head;

        while (fgets(line, BUFF_SIZE, project) != EOF)
        {
            // connect new node to the list
            newNode = loadNode(line);
            curr->next = newNode;
            // update current node to be the new one
            curr = newNode;
            
        }

        fclose(project);
    }
    else
    {
        printf("Error! canot open project, Creating a new project\n");
    }


    free(path);
    return head;
}

如果有人了解导致无限循环的原因,请在下方回答

【问题讨论】:

  • 将其剥离为实际的minimal reproducible example,提高警告级别并打开将警告视为错误,问题就变得明显了。 See here。我建议您提高警告级别,并且最肯定地将所有警告视为错误,因为在几乎所有情况下正是它们是什么。
  • 将 while (fgets(line, BUFF_SIZE, project) != EOF) 更改为 while (fgets(line, BUFF_SIZE, project))
  • @WhozCraig 您的评论实际上比当前的两个答案更好。

标签: c file data-structures linked-list


【解决方案1】:

如果遇到文件结尾并且没有读取任何字符,则fgets() 返回一个空指针,而不是 EOF。所以如果你检查!= EOF,你永远不会退出循环。

【讨论】:

    【解决方案2】:

    线

    while (fgets(line, BUFF_SIZE, project) != EOF)
    

    错了。

    fgets() 在成功时返回作为第一个参数传递的指针,在失败时返回 NULL。它不会返回EOF

    该行应该是:

    while (fgets(line, BUFF_SIZE, project))
    

    while (fgets(line, BUFF_SIZE, project) != NULL)
    

    【讨论】:

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