【问题标题】:Get terminal output into code [duplicate]将终端输出转换为代码[重复]
【发布时间】:2015-02-19 20:49:12
【问题描述】:

我写了一个程序来编译和运行一个外部程序(prog1.c)。我想以某种方式获得 prog1.c 的输出。
例如,如果 prog1.c 是 printf("HELLO"); 并将 HELLO 打印到终端,我希望此输出到达我的程序或文件中的变量。
我在某个地方看到了一些关于管道的东西,但我不太了解这个命令,也不知道这是否是正确的方法。

谁能帮助我、指导我或给我一个例子?
谢谢!

【问题讨论】:

  • 搜索“管道”、“popen”或“重定向”。

标签: c linux terminal output


【解决方案1】:

使用freopen,您可以将printf 输出重定向到文件。

freopen("c:\\output\\output.txt","w",stdout);
printf("write in file using printf"); //this will be printed to file, not to console

如果您想了解更多,可以在此查看我的video tutorial

在这个例子中,我没有使用管道,而是将标准输出重定向到文件而不是控制台。

【讨论】:

  • 谢谢!它看起来很容易使用
  • @marcopolo 它以写入模式打开文件。
  • @marcopolo 我提供了 freopen 参考的链接,以及我的视频教程。
  • 是的,我接受了。当我看到它时接受它还为时过早
【解决方案2】:

您还可以使用管道(和叉子)将输出从 prog1 重定向到您在另一个 prog 中的输入, 并检查 waitpid 以捕获返回值

【讨论】:

    猜你喜欢
    • 2016-11-01
    • 2013-11-29
    • 2016-03-07
    • 2019-04-11
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多