我最近开始学习 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 扫描它,然后接收下一个字符串并扫描它等等。但似乎发生的是 note.l 不会开始运行,除非 t.c 结束,这不是我想要的。所以我的问题是,我该如何补救?
提前致谢。
最佳答案
您可以更改 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 缓冲。
关于c - Flex 在 C 中使用管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578685/