-1

Okay so I'm trying to read in a PPM file (p3 format) and I want to read the comments (which are #s in ppm files).

The problem is that I don't know how to make C do what is in my head, heres what I want it to do.

read the file

where # appears, store all characters until the %\n character appears

repeat until all comments are read

I understand that I should be using some variations of getc, fgets and fscanf but I don't know how to apply them in this context.

I would put some code up showing what i've tried with getc, fgets and fscanf but to be brutally honest I have no idea how to use any of those functions and none of the info I can find seems to help and I really don't think any of my implementations are even doing anything.

Does anyone /is anyone willing to show me an example of how to parse a line with any of these functions?

4Ves
  • 53
  • 8

1 Answers1

1

Simple, two-state FSM, reading one character at a time:


#include <stdio.h>

int main(void)
{
int ch, state;

for(state=0;; ) {
        ch = getc(stdin);
        if (ch == EOF) break;
        if (state) {
                putc(ch, stdout);
                if (ch == '\n') state=0;
                continue;
                }
        if (ch == '#') state = 1;
        }
return 0;
}

Using ./a.out <fsm.c


include <stdio.h>
') state = 1;
wildplasser
  • 43,142
  • 8
  • 66
  • 109
  • Interesting, but how do I apply this to FILE IO as opposed to user IO. – 4Ves Feb 09 '21 at 13:37
  • What is FILE IO? What is user IO ? Is there a difference ? – wildplasser Feb 09 '21 at 13:38
  • what I mean is, I want to fopen a file and then parse through that. Doesn't stdin request user input from the console? – 4Ves Feb 09 '21 at 13:44
  • 1
    It would be exactly the same. The advantage of stdin/stdout is that you do not have to open them; they are already opened for you. Now, **you** do your homework. – wildplasser Feb 09 '21 at 13:48