如何将“ 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;
}
Medinoc

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章