Open In App

LEX program to add line numbers to a given file

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.




/* Program to add line numbers
 to a given file*/
%{
int line_number = 1;  // initializing line number to 1
%}
  
/* simple name definitions to simplify
the scanner specification name 
definition of line*/
line .*\n    
  
%%
{line} { printf("%10d %s", line_number++, yytext); } 
  
 /* whenever a line is encountered increment count*/
  
 /* 10 specifies the padding from left side to 
                    present the line numbers*/
   
 /* yytext The text of the matched pattern is stored
                           in this variable (char*)*/
%%
  
int yywrap(){} 
  
int main(int argc, char*argv[])
{
extern FILE *yyin;    // yyin as pointer of File type
  
yyin = fopen("testtest.c","r");  /* yyin points to the file 
                                   testtest.c and opens it
                                   in read mode.*/
  
yylex();   // The function that starts the analysis.
  
return 0;
}

Output:

Article Tags :