[英]C: Parsing a file with fgetc() - EOF infinite loop
Hello everbody @Stackoverflow, 大家好@Stackoverflow,
currently I am trying to write a simple parser for the .obj File format but somehow my parser is stuck in an infinite loop after reading the last comment in my file.txt. 目前,我正在尝试为.obj文件格式编写一个简单的解析器,但是在读取了file.txt中的最后一条注释后,解析器陷入了无限循环。 But it also happens in-between. 但这也发生在两者之间。
The parser should do following: 解析器应执行以下操作:
If the current char is a '#' it should print "COMMENT" and skip this line, if it is a 'v' it should print "VERTEX" and skip the line. 如果当前字符是“#”,则应打印“ COMMENT”并跳过此行;如果它是“ v”,则应打印“ VERTEX”并跳过该行。
Even though I stepped through my code with a debugger I still can't find the problem. 即使我使用调试器逐步执行了代码,也仍然找不到问题。
file.txt: file.txt:
# Comment1
# Comment2
# Comment3
v Vertex1
# Comment4
Code: 码:
int main()
{
FILE *file = fopen("file.txt", "r");
if(file==NULL)
{
return -1;
}
int currentChar=0;
while(currentChar!=EOF)
{
currentChar=fgetc(file);
printf("CURR CHAR: %c\n", currentChar);
switch(currentChar)
{
case '#':
{
printf("COMMENT\n");
currentChar=fgetc(file); //Read Whitespace 1x
while(currentChar!='\n')
currentChar=fgetc(file);
break;
}
case 'v':
{
printf("VERTEX\n");
currentChar=fgetc(file); //Read Whitespace 1x
while(currentChar!='\n')
currentChar=fgetc(file);
break;
}
}
}
return 0;
}
I still can not see where the problem lies. 我仍然看不到问题出在哪里。
Sincerely, toxic 真诚的,有毒的
It's looks like it's getting stuck waiting for a newline character. 看起来它在等待换行符时陷入困境。 The loop within your switch case is probably the culprit. 开关盒内的回路可能是罪魁祸首。 Change your loop to be: 将循环更改为:
while(currentChar != EOF && currentChar != '\n')
You probably want this: 您可能想要这样:
#include <stdio.h>
int main()
{
FILE *file = fopen("file.txt", "r");
if (file == NULL)
{
return -1;
}
int currentChar = 0;
while (currentChar != EOF)
{
currentChar = fgetc(file);
if (currentChar == EOF) // if EOF stop loop immediately,
// it's pointless to continue
break;
printf("CURR CHAR: %c\n", currentChar);
switch (currentChar)
{
case '#':
{
printf("COMMENT\n");
currentChar = fgetc(file);
while (currentChar != EOF && currentChar != '\n') // skip until \n or EOF
currentChar = fgetc(file);
break;
}
case 'v':
{
printf("VERTEX: <");
currentChar = fgetc(file);
while (currentChar != EOF && currentChar != '\n') // read until \n or EOF
{
printf("%c", currentChar);
currentChar = fgetc(file);
}
printf(">\n");
break;
}
}
}
return 0;
}
It's heavily based upon your original code. 这很大程度上取决于您的原始代码。 All comments are mine. 所有评论都是我的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.