c - 将 yyin 指向 mfcalc 示例中的 FILE*

标签 c bison

编辑:下面接受的解决方案。

我在这里处理 Bison mfcalc 示例: https://www.gnu.org/software/bison/manual/bison.html#Mfcalc-Main

我希望能够从文件而不是标准输入中读取。我已经启动并运行了他们的示例,但是因为他们已经重新定义了 yylex(),所以让解析器从文件中读取并不像通常那样简单。

任何可以提供帮助的人将不胜感激!

附言。像这样:http://beej.us/guide/bgc/output/html/multipage/getc.html 但我不太擅长 C。我会同时尝试实现它。

所以你需要修改这个:

int
yylex (void)
{
    int c;

    /* Ignore white space, get first nonwhite character.  */
    while ((c = getchar ()) == ' ' || c == '\t')
    continue;

    if (c == EOF)
    return 0;
    /* Char starts a number => parse the number.         */
    if (c == '.' || isdigit (c))
    {
        ungetc (c, stdin);
        scanf ("%d", &yylval.NUM);
        return NUM;
    }

    /* Char starts an identifier => read the name.       */
    if (isalpha (c))
    {
        /* Initially make the buffer long enough
         for a 40-character symbol name.  */
        static size_t length = 40;
        static char *symbuf = 0;
        symrec *s;
        int i;
        if (!symbuf)
        symbuf = (char *) malloc (length + 1);

        i = 0;
        do
        {
            /* If buffer is full, make it bigger.        */
            if (i == length)
            {
                length *= 2;
                symbuf = (char *) realloc (symbuf, length + 1);
            }
            /* Add this character to the buffer.         */
            symbuf[i++] = c;
            /* Get another character.                    */
            c = getchar ();
        }
        while (isalnum (c));

        ungetc (c, stdin);
        symbuf[i] = '\0';
        s = getsym (symbuf);
        if (s == 0)
        s = putsym (symbuf, VAR);
        *((symrec**) &yylval) = s;
        return s->type;
    }

    /* Any other character is a token by itself.        */
    return c;
}

最佳答案

这与 Bison 无关。

在 C 中,getcharstdin 中读取。如果您想使用不同的 FILE *,请改用 getc。因此,检查上面的 yylex 代码并将 getchar() 替换为 getc(yyin)(或任何 FILE * 的名称) ),并将所有其他对 stdin 的引用替换为 yyin。同样,scanfstdin 读取,而 fscanf 从不同的 FILE *

读取

关于c - 将 yyin 指向 mfcalc 示例中的 FILE*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294264/

相关文章:

c++ - 使 yylex 返回 symbol_type 而不是 int

c - 如何在 flex 和 bison 中获取 token 的字符串值?

c++ - 无法使用 typedef 结构解析字段 'tile'

c - C 中的 GLUT 屏幕截图

bison - 我怎样才能有 "implicit multiplication"规则与 Bison?

c++ - 如何告诉 flex 和 bison 停止处理输入?

c++ - Bison 的错误 : request for member ‘charTokens’ in something not a structure or union

c - 如何使用 'key' : C 进行排序

c - 如何删除此警告 : second parameter of ‘va_start’ not last named argument?

c++ - 使用 ReadFile() 简单读取文件