tags:

views:

280

answers:

2

Suppose I want my Lex and Yacc program to parse the command line arguments like:

./a.out show memory

I want lex to parse the string "show memory". How do I accomplish this?

+1  A: 

You'll need to concatenate all the arguments into a big string, by inserting whitespace between them. Then feed the remaining text buffer to Lex/Yacc, by re-defining the YY_INPUT macro so it reads input from your text buffer.

The start could be something like:

#include <stdio.h>
#include <string.h>

char *argbuf;
size_t arglen;

int main(int argc, char *argv[])
{
  int i;

  // Compute total length of all arguments, with a single space between.
  arglen = 0;
  for(i = 1; argv[i] != NULL; i++)
    arglen += 1 + strlen(argv[i]);

  // Allocate buffer space.
  argbuf = malloc(arglen);
  if(argbuf == NULL)
  {
     fprintf(stderr, "No memory for argument buffer, aborting");
     exit(1);
  }

  // Concatenate all arguments. This is inefficient, but simple.
  argbuf[0] = 0;
  for(i = 1; argv[i] != NULL; i++)
  {
    if(i > 1)
      strcat(argbuf, " ");
    strcat(argbuf, argv);
  }

  // Here we should be ready to call yyparse(), if we had implemented YY_INPUT().

  return 0;
}
unwind
could u please tell me how to modify YY_INPUT in the above case i mentioned.
ajai
@ajai: Follow the link, it shows an example.
unwind
i am getting these errors when i try the above codetry.y:8: error: syntax error before '{' tokentry.y:10: error: `c' undeclared here (not in a function)try.y:10: error: `EOF' undeclared here (not in a function)try.y:10: error: `YY_NULL' undeclared here (not in a function)try.y:10: error: `buf' undeclared here (not in a function)try.y:10: warning: data definition has no type or storage classtry.y:11: error: syntax error before '}' token
ajai
@ajai: It's easier to help you if you simply edit your question with any additional information.
unwind
@unwind: ok as i said i want to parse the arguements which i give to executable file. for eg: ajai show memory. where ajai is the executable file and show memory are the arguements. when i redefined yy_input as given in the example still it is not reading the arguements so pls tell me how to go about it
ajai
@ajai: I meant you shouldn't post new comments, you should edit the original question, above. But perhaps you can't (due to reputation requirements), I'm not sure how it works.
unwind
@unwind, Pretty sure he can always edit his own questions.
mrduclaw
A: 

What's wrong with doing it the old fashioned way?:

if(argc > 1 && !strcmp(argv[1],"show"))
{
    if(argc > 2)
    {
        if(!strcmp(argv[2],"memory"))
            ...
        else if(!strcmp(argv[2],"cpu"))
            ...
        else ...
    }
}

Besides, getopt() and friends are more appropriate.

iWerner
no i can't use dis method bcoz i have 20 keywords . moreover there is no order in which dey should occur
ajai
OK, go with unwind's method then, but I smell over engineering.
iWerner