Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the output of one C program into a variable in another C program

I have 2 C programs. Say one is program-1.c

int main(){
printf("hello world");
}

Now in 2nd code named program-2.c, I want the output of 1st code into a variable, so that I can have the output "hello world" into a variable in the 2nd C code.

How can I do this?

like image 794
Ronin Avatar asked Jan 04 '12 07:01

Ronin


3 Answers

You can use the popen function for this:

FILE* proc1 = popen("./program1", "r");
// Usual error handling code goes here
// use the usual FILE* read functions
pclose(proc1);
like image 171
Mat Avatar answered Sep 27 '22 22:09

Mat


You will need to run the two programs in two separate processes and then use some sort of IPC mechanism to exchange data between the two processes.

like image 21
Alok Save Avatar answered Sep 27 '22 21:09

Alok Save


On many operating systems you can get the output from one console program as input to the next, perhaps

program-1 > program-2

you can then read the result from standard input

std::string  variable;

std::getline(std::cin, variable);
like image 21
Bo Persson Avatar answered Sep 27 '22 23:09

Bo Persson