Skip to content
Related Articles

Related Articles

Improve Article

Lex Program to remove comments from C program

  • Difficulty Level : Basic
  • Last Updated : 28 Aug, 2019

Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

The commands for executing the lex program are:

lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out

Let’s see LEX program to accept string starting with vowel.
Examples:

Input : 
//testing
#include 
int main()
{
 /* multiline comment
    continue....
 */
 return 0;
}

Output :
#include 
int main()
{
 
 return 0;
}

Below is the implementation:




/% Lex Program to remove comments from C program 
   and save it in a file %/
/*Definition Section*/
%{
%}
  
/*Starting character sequence for multiline comment*/
start \/\*
/*Ending character sequence for multiline comment*/
end  \*\/
  
/*Rule Section*/
%%
  
/*Regular expression for single line comment*/
\/\/(.*) ;
/*Regular expression for multi line comment*/ 
{start}.*{end} ;
  
%%
  
/*Driver function*/
int main(int k,char **argcv)
{
yyin=fopen(argcv[1],"r");
yyout=fopen("out.c","w");
/*call the yylex function.*/
yylex();
return 0;
}

Output:



Go Premium (An Ad Free Experience with many more features)

My Personal Notes arrow_drop_up
Recommended Articles
Page :