c - 如何将 "bc"的输出存储到变量中?

标签 c fork bc

这个程序应该做的是问用户一个简单的算术问题,例如5 + 7 然后用“bc”检查答案(是否正确)。

我有以下代码,但我不明白如何编辑它以将“5 + 7”的结果存储到变量中(目前结果进入 STDOUT)。

欢迎任何帮助。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main( int argc, char *argv[], char *env[] )
{

    char *expr = "5 + 7\n";
    int answer;

    printf("%s = ", expr);
    scanf("%d", &answer);


    int pfds[2];
    pipe(pfds);

    if (!fork()) {
        close(1);       /* close normal stdout */
        dup(pfds[1]);   /* make stdout same as pfds[1] */
        close(pfds[0]); /* we don't need this */
        printf("%s\n", expr);

        /***********************/
        /* How to store printf()'s output into a variable? */

        exit(0);
    } else {
        close(0);       /* close normal stdin */
        dup(pfds[0]);   /* make stdin same as pfds[0] */
        close(pfds[1]); /* we don't need this */
        execlp("bc", "bc", NULL);
    }


   return 0;
}

最佳答案

您需要创建第二个管道并在子进程中将 stdout 重定向到它。

关于c - 如何将 "bc"的输出存储到变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20325944/

相关文章:

c - roll() 函数导致的未定义行为(使用 C)

C 预处理器魔法

在 child 退出之前无法从流中读取?

c - execvp - 为什么我的程序退出?

以多进程方式计算斐波那契数?

base - bc 及其 ibase/obase 选项 :

c - 在任何情况下,将 const 多次放在变量上会有用吗?

c - 如果不使用 C 中的逻辑运算符、关系运算符或选择结构,如何将 11,12 和 13 的值分配给所有等于 10 的值?

Bash 十进制到 base 62 的转换

bash - `printf "2+2 "| bc` 返回语法错误,`echo "2+2 "| bc` 有效,它们如何以不同的方式处理字符串?