Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex: Use Text File as Input Stream

Tags:

c

flex-lexer

lex

So I've used flex to generate a c file from my lex code, and then used gcc to create the corresponding actual parser .exe. However, I can't figure out how to get it to read from anything other than my own typed input. I am trying to get it to parse a huge dictionary file. Can anyone help?

like image 714
John Roberts Avatar asked Feb 02 '13 20:02

John Roberts


3 Answers

You have two ways of solving it. The first is to redirect input from standard input with the command prompt < operation:

> parser.exe < some_file.txt

The other solution is to let the program open the file, and tell the lexer what the file is. For more information about it see the Flex manual. The important functions are yy_create_buffer and yy_switch_to_buffer.

like image 118
Some programmer dude Avatar answered Nov 03 '22 22:11

Some programmer dude


Try to add the following code to your *.l file.

int main(int argc, char *argv[])
{
    yyin = fopen(argv[1], "r");
    yylex();
    fclose(yyin);
}
like image 20
leoly Avatar answered Nov 03 '22 22:11

leoly


Adding onto the above answer by @Eliko, while using flex with yacc/bison, you can define FILE *yyin; in the global part of your grammar.y file. The definition in the generated lex.yy.c is an extern FILE *yyin by default. Thus, in your grammar.y, do something like this:

/* Some other global definitions */
FILE *yyin;
%%
/* Grammar rules*/
/* Grammar rules*/
%%
void main(int argc, char **argv) {
  /* Process command line args*/
  yyin = fopen("input.c", "r");
  yyparse();
  fclose(yyin);
  return 0;
}
like image 9
forumulator Avatar answered Nov 04 '22 00:11

forumulator