我正在C中创建一个GIF程序。文件管理的一部分是将一个.txt文件加载到一个链接列表中。我想用fget逐行加载,但出于某种原因,我的程序进入了一个无限循环。下面是我写的代码:
/*
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;
}
如果有人了解导致无限循环的原因,请在下面回答
发布于 2021-07-01 11:19:25
线
while (fgets(line, BUFF_SIZE, project) != EOF)
是错的。
fgets()
返回作为成功的第一个参数传递的指针,在失败时返回NULL
。它不会返回EOF
。
这一行应是:
while (fgets(line, BUFF_SIZE, project))
或
while (fgets(line, BUFF_SIZE, project) != NULL)
发布于 2021-07-01 11:28:00
如果遇到文件末尾而没有读取字符,则fgets()
将返回一个空指针,而不是EOF。因此,如果您检查是否为!= EOF
,则永远不会退出循环。
https://stackoverflow.com/questions/68209186
复制相似问题