Skip to content

Instantly share code, notes, and snippets.

@dwf
Created February 1, 2010 21:13
Show Gist options
  • Save dwf/292039 to your computer and use it in GitHub Desktop.
Save dwf/292039 to your computer and use it in GitHub Desktop.
A lexer for portable graymap (PGM) files. Use lex or flex to compile into C code.
/* Scanner that reads in a Portable Graymap (PGM) file.
*
* By David Warde-Farley -- user AT cs dot toronto dot edu (user = dwf)
* Redistributable under the terms of the 3-clause BSD license
* (see http://www.opensource.org/licenses/bsd-license.php for details)
*/
enum { PRE_START, PARSE_START, GOT_X, GOT_Y, GOT_MAX } parserstate
= PRE_START;
int xDim, yDim, max, whichval = 0;
int *vals;
DIGIT [0-9]
COMMENT ^#.*
FILEFORMAT P2
%%
{FILEFORMAT} {
parserstate = PARSE_START; /* The real data should be coming up. */
}
{DIGIT}+ {
switch (parserstate) {
case PARSE_START:
xDim = atoi(yytext);
parserstate = GOT_X;
break;
case GOT_X:
yDim = atoi(yytext);
parserstate = GOT_Y;
vals = malloc(xDim * yDim * sizeof(int));
break;
case GOT_Y:
max = atoi(yytext);
parserstate = GOT_MAX;
break;
case GOT_MAX:
vals[whichval++] = atoi(yytext);
break;
}
}
{COMMENT} /* We don't care about comments. */
[\n ]+ /* Eat up whitespace & newlines. */
%%
int
main(int argc, char **argv)
{
++argv, -- argc;
if (argc > 0)
yyin = fopen(argv[0], "r");
else
yyin = stdin;
yylex();
printf("Read %dx%d PGM file, max value of %d; %d total vertices.\n",
xDim, yDim, max, whichval);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment