Experiment No 2
Exp no 2. Parsing a Command Line:
The command
line parameters are the parameters that are appearing on the shell prompt.
The command
line interface is the interface which allows the user to interact with the
computer by typing the commands.
In C we can
pass these parameters to the main function in the form of character array.
For example:
$
cp abc.txt pqr.txt
Here
argv[0]=cp
argv[2]=pqr.txt
Now in this
experiment we want to handle the command line parameters with using LEX
specification file.
Example: Lex program to check well formedness
of the parenthesis by using command line arguments.
LEX Program:
%{
#include<stdio.h>
#include<string.h>
char temp[10];
int
i=0,openbracket=0,closebracket=0;
extern FILE *yyin;
%}
%%
"("[()]*")"";"
{
strcpy(temp,yytext);
printf("%s\n",temp);
i=0;
while(temp[i]!=';')
{
if(temp[i]=='(')
openbracket++;
if(temp[i]==')')
closebracket++;
else;
i++;
}
if(openbracket==closebracket)
printf("Well formed
input!\n");
else
printf("not well
formed!\n");
}
%%
main(int argc,char *argv[])
{
FILE
*fp=fopen(argv[1],"r");
yyin=fp;
yylex();
fclose(fp);
}
yywrap()
{
return 1;
}
Input file
named “b.c” contains ( ( )( ) ) ;
Program Explanation:
In the above program, we have used a
file b.c which is our input file. While running the LEX program we have given
the program via the input file “b.c”using command line parameter.
Note that,
argv[0]=”./a.out”
argv[1]=”b.c”
In the main() function we have opened the file
“b.c” in read mode by
Fp=fopen(argv[1],”r”);
The file
pointer fp of the opened file “b.c” will then be assigned to the standard input
file pointer yyin as,
Extern FILE *yyin;
Then the
yylex routine is invoked to call LEX.
The logic of
the above program is very simple. We have maintained one temp array in which
the input expression is copied.
For example:
(
|
(
|
)
|
(
|
)
|
)
|
;
|
temp[]
Then we have
maintained two counters ‘openbracket’ and ‘closebracket’.
As soon as we
come across the openbracket the ‘openbracket’ counter will be incremented and
as soon as we come across the closing bracket, the ‘closebracket’ counter will
be incremented.
The regular
expression specifies that opening bracket should occur prior to closing brace.
The same logic works until we get the semicolon.
If both the
‘openbracket’ & ‘closebracket’ counters are same then declare “Well formed
input!”
Otherwise
declare “not well formed!”
Steps to Execute:
1.
vi well.l
2.
lex well.c
3.
cc lex.yy.c
4.
./a.out b.c
Output:
Content of input file
|
Ouput
|
e.g ( ( ) ( ) ) ;
|
Well formed input!
|
Comments
Post a Comment