我有一个通过popen()
运行bc
的代码。我可以拦截计算器的输出并在其前面添加“Output=”文本。但是我如何拦截用户正在写入 bc
的内容?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *in;
char buff[512];
if(!(in = popen("bc", "r"))){
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL){
printf("Output = %s", buff);
}
pclose(in);
return 0;
}
最佳答案
您可以将 bc
和 echo
与管道结合起来:echo '12*4' | BC
输入 12*4
的示例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
FILE *in;
char buff[512];
char cmd[512];
while (fgets(buff, sizeof(buff), stdin)!=NULL){
strcpy(cmd, "echo '");
strcat(cmd, buff);
strcat(cmd, "' | bc");
if(!(in = popen(cmd, "r"))){
exit(1);
}
fgets(buff, sizeof(buff), in);
printf("output:%s", buff);
}
pclose(in);
return 0;
}
输出:
david@debian:~$ ./demo
12*4
output:48
关于c - popen:拦截用户的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38703496/