LEX program to add line numbers to a given file
Last Updated :
30 Apr, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt.
Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Prerequisite: Flex (Fast lexical Analyzer Generator)
Example:
Input:
#include<stdio.h>
// Driver Code
int main()
{
int a;
/* we have to delete comments */
return 0;
}
Output:
1 #include<stdio.h>
2 // Driver Code
3 int main()
4 {
5 int a;
6 /* we have to delete comments */
7 return 0;
8 }
Approach:
A new line is encountered because of the /n. To count the number of lines, count the number of /n occurred with initial value as 1 as there exists an initial single line. All the other things can be ignored as focus is on number of /n. Take a counter initially set to 1 and increment it whenever a new line (/n) occurs.
Input File: testtest.c
Below is the implementation to add line numbers to a given file.
%{
int line_number = 1;
%}
line .*\n
%%
{line} { printf ( "%10d %s" , line_number++, yytext); }
%%
int yywrap(){}
int main( int argc, char *argv[])
{
extern FILE *yyin;
yyin = fopen ( "testtest.c" , "r" );
yylex();
return 0;
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...