How to make YY_INPUT point to a string rather than stdin in Lex & Yacc (Solaris)

后端 未结 5 815
礼貌的吻别
礼貌的吻别 2020-12-01 16:55

I want my yylex() to parse a string rather than a file or standard input. How can I do it with the Lex and Yacc provided with Solaris?

5条回答
  •  独厮守ぢ
    2020-12-01 17:32

    Here is something that should work with any implementation, although risky by using popen.

    $ cat a.l
    %%
    "abc" {printf("got ABC\n");}
    "def" {printf("got DEF\n");}
    . {printf("got [%s]\n", yytext);}
    %%
    int main(int argc, char **argv)
    {
        return(lex("abcdefxyz"));
    }
    lex(char *s)
    {
        FILE *fp;
        char *cmd;
        cmd=malloc(strlen(s)+16);
        sprintf(cmd, "/bin/echo %s", s); // major vulnerability here ...
        fp=popen(cmd, "r");
        dup2(fileno(fp), 0);
        return(yylex());
    }
    yywrap()
    {
        exit(0);
    }
    $ ./a
    got ABC
    got DEF
    got [x]
    got [y]
    got [z]
    

提交回复
热议问题