c - popen:拦截用户的输入

标签 c popen

我有一个通过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;
}

最佳答案

您可以将 bcecho 与管道结合起来: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/

相关文章:

Python Popen shell=False 导致 OSError : [Errno 2] No such file or directory

c - 如何从 C 函数将树遍历作为数组返回

c - 它是可移植的编译库吗?

c - 如何找到整数数组的大小

Python - 使用 Popen 中的列表作为命令

记事本的 Python 子进程

c - 使用 popen 时出现意外的 sh 语法错误

c - 为什么这个快速排序有效?

arrays - c 函数是否可以同时接受 double 和 long double 参数?

C语言 : popen() with fread()?