Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C run external program and get the result

Tags:

c

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

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.

like image 898
manatails008 Avatar asked Dec 07 '22 00:12

manatails008


1 Answers

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.

like image 115
Sam Avatar answered Dec 29 '22 04:12

Sam