c - 在 Lex 中解析命令行参数

标签 c yacc lex flex-lexer

假设我希望我的 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/

相关文章:

c - C 中的宏生成宏?

在 Bison 中找不到 'syntax error' 消息的原因

python - 如何忽略 ply.yacc 中的标记

在 (f)lex 中复制整个输入行(以获得更好的错误消息)?

c++ - 在 Windows 7 上使用 SHA2-512 (CALG_SHA_512) 返回 "Invalid Algorithm Specified"

c++ - 如果未定义检查的 bool 宏,则生成错误

c - 矩阵乘法 - C

c++ - 添加printf语句时NULL指针异常消失

c++ - 声明类变量c++

c - 解析器的左联想语法