C运行外部程序,并得到结果 [英] C run external program and get the result

查看:244
本文介绍了C运行外部程序,并得到结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,我应该如何执行外部程序,并得到其结果,如果它是在控制台中运行?

In C, how should I execute external program and get its results as if it was ran in the console?

如果有一个称为虚拟可执行文件,并显示在命令提示符下4位数执行时,我想知道如何运行的可执行文件,并得到它已经产生的4位数字。在C

if there is an executable called dummy, and it displays 4 digit number in command prompt when executed, I want to know how to run that executable and get the 4 digit number that it had generated. In C.

推荐答案

的popen()处理这个相当不错。举例来说,如果你要调用的,通过线读取结果行:

popen() handles this quite nicely. For instance if you want to call something and read the results line by line:

char buffer[140];
FILE *in;
extern FILE *popen();
if(! (in = popen(somecommand, "r"""))){
    exit(1);
 }

 while(fgets(buff, sizeof(buff), in) != NULL){
      //buff is now the output of your command, line by line, do with it what you will
 }
 pclose(in);

这为我工作之前,希望这是有帮助的。确保包括以使用标准输入输出。

This has worked for me before, hopefully it's helpful. Make sure to include stdio in order to use this.

这篇关于C运行外部程序,并得到结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆