假设我希望我的 Lex 和 Yacc 程序解析如下命令行参数:
./a.out show memory
我希望 lex 解析字符串“show memory”。我该如何实现?
最佳答案
您需要通过在它们之间插入空格将所有参数连接成一个大字符串。然后通过重新定义 <a href="http://www.delorie.com/gnu/docs/flex/flex_10.html" rel="noreferrer noopener nofollow">YY_INPUT</a>
将剩余的文本缓冲区提供给 Lex/Yacc。宏,以便它从您的文本缓冲区读取输入。
开头可能是这样的:
#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;
}
关于c - 在 Lex 中解析命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1906747/