8.Reading and Writing using Files with examples

By default yyin and yyout points to the stdin and stdout.We can set yyin to point to a different file so that flex will read the contents from the file pointed by yyin.Similarly yyout can point to output file.

The following program will find number of lines,words and characters in a text file "text.dat"( similar to wc command in linux)

%{
      int nchar, nword, nline;
%}
%%
\n             { nline++; nchar++; }
[^  \t\n]+ { nword++, nchar += yyleng; }
.               { nchar++; }
%%
int main(void)
{
yyin=fopen("text.dat","r");
yylex();
printf("%d\t%d\t%d\n",nline,nword,nchar);
return 0;
}

The program below reads a text file passed as argument and display each line with line number.
%{
int lineno;
%}
%%
^(.*)\n printf("%4d\t%s", ++lineno, yytext);
%%
int main(int argc, char *argv[])
{
yyin = fopen(argv[1], "r");
yylex();
flose(yyin);
}

The program below reads a data file num.dat which contains integer and floats and append integers into int.dat and floats into float.dat

DIG [0-9]
%%
{DIG}+ {yyout=fopen("int.dat","a");ECHO;}
{DIG}+"."{DIG}* {yyout=fopen("float.dat","a");ECHO;}
%%
main()
{
yyin=fopen("num.dat","r");
yylex();
fclose(yyin);
flcose(yyout);
}

The following program will copy non blank lines from file x to file y
%%
[ \t]*\n    ;
.*\n   {fprintf(yyout,"%s",yytext);}
%%
main()
{
yyin=fopen("x","r");
yyout=fopen("y","w");
yylex();
}
The following program will remove all multi line comments from a C program 't.c' and write to a new file 'tnew.c'.
%x comm
%%
"/*" {BEGIN(comm);}
<comm>[^*]*
<comm>"*"+[^/]
<comm>"*"+"/" BEGIN(INITIAL);
%%
main()
{
yyin=fopen("t.c","r");
yyout=fopen("tnew.c","w");
yylex();
}
 

Comments

Popular posts from this blog

KTU Compiler Lab CSL411

13.Precedence and conflict resolution in yacc

1.Introducion to lex/flex