【问题标题】:Flex using Pipes in C在 C 中使用管道进行 Flex
【发布时间】:2017-06-15 23:48:42
【问题描述】:

我最近开始学习 Flex,我有一个问题。我有一个简单的 C 代码,可以打印几个字符串,我希望这个程序的输出成为 flex 程序的输入。为此,我尝试了以下命令:

./t | ./note

t.c 的代码:

#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv){

    printf("alfred nota: 79 \n");
    fflush(stdout);
    sleep(5);
    printf("alfred nota: 79 \n");
    fflush(stdout);
    printf("alfred nota: 79 \n");
    fflush(stdout);

    return 0;
}

note.l 的代码

%{
%}

%%
"nota: 79" { printf("Saiu nota 79\n"); }
.|\n  {;}
%% 

int yywrap(){
    return(1);
}

int main(){
    yylex();
    return(0);
}

我想要的是让 flex 程序从 t.c 程序接收一行并用 note.l 扫描它,然后接收下一个字符串并扫描它,依此类推。但似乎发生的是,除非 t.c 结束,否则 note.l 不会开始运行,这不是我想要的。所以我的问题是,我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: c operating-system flex-lexer


    【解决方案1】:

    您可以更改 flex 行为以使用 read 而不是 stdio:

    这可以通过以下两种方式之一完成:

    选项 1

    使用-Cr 生成您的词法分析器:

    flex -Cr -o note.c note.l
    

    或者

    选项 2

    把它放到你的 lex 文件中:

    %{
    %}
    
    %option read
    %%
    "nota: 79" { printf("Saiu nota 79\n"); }
    .|\n  {;}
    %% 
    
    int yywrap(){
        return(1);
    }
    
    int main(){
        yylex();
        return(0);
    }
    

    使用 read 会关闭 flex 的 io 缓冲。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多