I am trying to write a program using Lex which recognizes some letters, numbers and do minor things. The problem is that the program does not recognizes anything. In fact, I changed the rules to a simple rule to recognizes everything, but still does nothing. What's happening? Maybe it's simple (it must be, there are few lines), but I am new with Lex and I am not able to fix it. Thanks
simple.l:
%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int count = 0;
%}
/*Reglas*/
%%
[a-zA-Z_]*[a-zA-Z_0-9]* { count++; printf("%s ", yytext); }
.* { count++; printf("%s ", yytext); }
%%
/*Procedimientos de usuario*/
int main(int argc, char * argv[]) {
FILE * yyin;
if(argc == 2) {
yyin =fopen(argv[1],"rt");
if(yyin == NULL) {
printf("File %s can not be opened\n", argv[1]);
exit(-1);
}
} else {
printf("Error in arguments");
exit(-1);
}
yylex();
printf("Counter : %d \n", count);
fclose(yyin);
return 0;
}
Imput file: example.txt
CSC104H1
CSC108H1
CSC204H1
CSC258H1
Also, I need to use ctrl+d to finish the program(as I saw in stackoverflow), if not, the program does not finish by itself.
int main(int argc, char * argv[]) {
FILE * yyin;
// ...
yyin = ....
}
Here, yyin
is a local variable. The scanner is using the global variable with the same name, which this declaration is shadowing.
Delete the declaration and it will work fine.
Your first clue is that the scanner is evidently reading from standard input, not from the file you specified, which is why it waits for you to type an end-of-file indicator.