/* Scanner that reads in a Portable Graymap (PGM) file. * * Copyright (c) 2005 David Warde-Farley * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 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; }