【发布时间】: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