Friday, September 9

LEX Program to delete all comments


No Comments  :)


This lex program is intended to eliminate comments from a C program. This task is simple since in a C program, comments will be associated only with '//' or '/*...*/ only. So our aim is to detect the occurence of these characters and ignore subsequent comments.



%{
#include<stdio.h>
%}


%%

\/\/.* ;
\/\*(.*\n)*.*\*\/ ;

%%

main()
{
yyin=fopen("mypgm.c","r");
yylex();
}


int yywrap()
{
return 1;
}





\/\/.* ; eliminates single line coments. i.e., comments of the form ' //comment.. .. .. ;'
It simply look on '/'immediately followed by another '/' and ignore that line.

\/\*(.*\n)*.*\*\/ ; eliminates multiple comments. i.e, code fragment lies within /*...*/


Have  a look on this Example:

Consider mypgm.c

//This is a single comment;
This is not a comment;
/*But..
These are mulptiple comments
*/
Again, It is not a comment


The output will be,

This is not a comment;
Again, It is not a comment

8 comments :

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Please give proper solution...
can anyone tell how does lex program work???

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

more than 1 multi line comments will result into a greedy match... eliminating the code in between too...

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

@Anonymousletter [a-zA-z]
digit [0-9]
%%
"if"|"else"|"for"|"while"|"do" printf("KeyWord %s\n",yytext);
"?"/[^:]*":" printf("Ternary %s\n",yytext);
\"[^\"]*\" printf("String Literal %s\n",yytext);
"/*"[^*]*"*/"|"/*"[^/]*"*/" ;
\/\/.* ;
%%
main(int argc,char *argv[])
{
yyin=fopen(argv[1],"r");
yyout=fopen(argv[2],"w+");
yylex();
}

Unknown said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Its to a great degree informational, smart and quality substance. I wish every one of you favorable circumstances for your coming locales and posts. Keep sharing!. wp plugins

sbobet said... Best Blogger Tips [Reply to comment] Best Blogger Templates

i dont know

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

What about a string containing /*.
Eg-
printf("This is a comment - /* comment*/");
This should not be removed.

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

@Anonymous

+1

Unknown said... Best Blogger Tips [Reply to comment] Best Blogger Templates

can you please explain how the remaining code is printed? where is printing line in main program

Post a Comment