Lex program to add line numbers to a given file and create a new file
Lex program to add line numbers to a given file and create a new file
**************************************************
%{
int line_number = 1;
%}
%option noyywrap
line .*\n
%%
{line} { printf("%10d %s", line_number, yytext); fprintf(yyout,"%10d %s",line_number,yytext);line_number++; }
%%
int main()
{
yyin = fopen("test.c","r");
yyout=fopen("testnew.c","w");
yylex();
return 0;
}
Execution
$cat test.c # input file
#include <stdio.h>
void main()
{
int a=2,b=4;
printf("%d",a+b);
}
$flex lnumber.lex
$ gcc lex.yy.c
$ ./a.out
1 #include <stdio.h>
2 void main()
3 {
4 int a=2,b=4;
5 printf("%d",a+b);
6 }
$cat testnew.c # new file created
1 #include <stdio.h>
2 void main()
3 {
4 int a=2,b=4;
5 printf("%d",a+b);
6 }
Comments
Post a Comment