Lex program to count the number of comment lines in C program

 

Lex program to count the number of comment lines in a given C program and eliminate the comments and write into the output file

Problem definition:

Write a lex code to count the number of comment lines in a given C program. Also, eliminate them and copy the resulting program into a separate file.

Structure of LEX Program:

%{
Definition section
%}

%%
Rules section
%%

User Subroutine section  

Click here to learn – How to Compile & Run LEX / YACC Programs on Windows 8, 10, and 11?

Source Code to count the number of comment lines in the C program

%{
#include<stdio.h>
int nc=0;
%}

%%
"/*"[a-zA-Z0-9\n\t ]*"*/"  {nc++;}
"//"[a-zA-Z0-9\t ]*"\n"   {nc++;}
%%

int main(int argc ,char* argv[])
{
	if(argc==2)
	{
		yyin=fopen(argv[1],"r");
	}
	else
	{
		printf("Enter the input\n");
		yyin=stdin;
	}
	yyout=fopen("output.c","w");
	yylex( );
	printf("The number of comment lines=%d\n",nc);
	fclose(yyin);
	fclose(yyout);
}

int yywrap( )
{
	return 1;
}

Output:

input.c is the input file for the program

void main()
{
	int a; // integer variable
	float b; /* float variable */
	/* Multiline
	Comment */
	fun(); // function call
}

maheshgh@maheshgh:~/LexYacc$ lex demo.l

maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c

maheshgh@maheshgh:~/LexYacc$ ./a.out input.c

The number of comment lines=4

output.c is the output file for the program

void main()
{
int a; float b; 

fun(); 
}

Summary:

This article discusses how to write a program to count the number of comment lines in a given C program. Also, eliminate them and copy the resulting program into a separate file. If you like the article, do share it with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *