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

I have 2 C programs. Let's say that thisprogram-1.c

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

Now in the second code with the name program-2.cI want the output of the 1st code in the variable, so that I can get the output of "hello world" in the variable in the second C code.

How can i do this?

+5
source share
6 answers

You can use the function popenfor this:

FILE* proc1 = popen("./program1", "r");
// Usual error handling code goes here
// use the usual FILE* read functions
pclose(proc1);
+10
source

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

+2
source

, ,

program-1 > program-2

std::string  variable;

std::getline(std::cin, variable);
+2

" - " "

#include <unistd.h>
#include <process.h>

/* Pipe the output of program to the input of another. */

int main()
{
  int pipe_fds[2];
  int stdin_save, stdout_save;

  if (pipe(pipe_fds) < 0)
    return -1;

  /* Duplicate stdin and stdout so we can restore them later. */
  stdin_save = dup(STDIN_FILENO);
  stdout_save = dup(STDOUT_FILENO);

  /* Make the write end of the pipe stdout. */
  dup2(pipe_fds[1], STDOUT_FILENO);

  /* Run the program. Its output will be written to the pipe. */
  spawnl(P_WAIT, "/dev/env/DJDIR/bin/ls.exe", "ls.exe", NULL);

  /* Close the write end of the pipe. */
  close(pipe_fds[1]);

  /* Restore stdout. */
  dup2(stdout_save, STDOUT_FILENO);

  /* Make the read end of the pipe stdin. */
  dup2(pipe_fds[0], STDIN_FILENO);

  /* Run another program. Its input will come from the output of the
     first program. */
  spawnl(P_WAIT, "/dev/env/DJDIR/bin/less.exe", "less.exe", "-E", NULL);

  /* Close the read end of the pipe. */
  close(pipe_fds[0]);

  /* Restore stdin. */
  dup2(stdin_save, STDIN_FILENO);

  return 0;
}

....

+1

...

#include <iostream>
#include<time.h>
 
using namespace std;
 
int main()
{
    int a=34, b=40;
 
    while(1)
    {
        usleep(300000);   
        cout << a << " " << b << endl;
    }
}



#include<iostream>
 
using namespace std;
 
int main()
{
    int a, b;
 
    while(1)
    {
    cin.clear();
 
        cin >> a >> b;
 
        if (!cin) continue;
 
        cout << a << " " << b << endl;
    }
}

usleep() . . ..:)

0

-2.c int argc char *argv[] -1.c

, -2.c :

void main(int argc, char *argv[]) 
{
   int i;

   for( i=0; i<argc; i++ ) 
   {
        printf("%s", argv[i]); //Do whatever you want with argv[i]
   }       

}

program-1 > program-2

0
source

All Articles