Search code examples
cparsinginfinite-loopeoffgetc

C: Parsing a file with fgetc() - EOF infinite loop


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


Solution

  • 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.