Reputation: 3
Hello everbody @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. 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.
Even though I stepped through my code with a debugger I still can't find the problem.
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
Upvotes: 0
Views: 1562
Reputation: 111
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')
Upvotes: 2
Reputation: 50775
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.
Upvotes: 0