Could anyone please help me in writing a LEX program to check and count comment lines in a C program. I have searched for it everywhere and failed to get the complete code.
comment lines are of the form
%% {START} {whatever symbols,alphanumerics and letters} {END} %%
Here is a sample code to do it
`
%{
#include<stdio.h>
int c=0;
%}
START "/*"
END "*/"
SIMPLE [^*]
SPACE [ \t\n]
COMPLEX "*"[^/]
%s newstate
%%
"//"(.*[ \t]*.*)*[\n]+ {c++; fprintf(yyout," ");}
{START} {yymore();BEGIN newstate;}
<newstate>{SIMPLE} {yymore();BEGIN newstate;}
<newstate>{COMPLEX} {yymore();BEGIN newstate;}
<newstate>{SPACE} {yymore();BEGIN newstate;}
<newstate>{END} {c++;fprintf(yyout," ");BEGIN 0;}
%%
main()
{//program to remove comment lines
yyin=fopen("file4","r");
yyout=fopen("fileout4","w");system("cat file4");
yylex();system("cat fileout4");
printf("no.of comments=%d",c);
fclose(yyin);
fclose(yyout);
}
`
The input file "file4" is below
/* #include <stdlib.h>
{}.@All nonsense symbols */
//another comment
int main{}
{/**/
printf("hello");
/* comment inside// comment is ignored */
//how about//this?
/* now we /* try this */ */
printf("COOL!!");
return (0);
}
It gives the following output which is stored in "fileout4" `
int main{}
{
printf("hello");
*/
printf("COOL!!");
return (0);
}
`
The number of comment lines in the above program is 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With