How do i run a program from another program and pass data to it via stdin in c or c++?

In C on platforms whose name end with X (i.e. not Windows), the key components are:

  1. pipe - Returns a pair of file descriptors, so that what's written to one can be read from the other.

  2. fork - Forks the process to two, both keep running the same code.

  3. dup2 - Renumbers file descriptors. With this, you can take one end of a pipe and turn it into stdin or stdout.

  4. exec - Stop running the current program, start running another, in the same process.

Combine them all, and you can get what you asked for.


The easiest way I know for doing this is by using the popen() function. It works in Windows and UNIX. On the other way, popen() only allows unidirectional communication.

For example, to pass information to sum.exe (although you won't be able to read back the result), you can do this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *f;

    f = popen ("sum.exe", "w");
    if (!f)
    {
        perror ("popen");
        exit(1);
    }

    printf ("Sending 3 and 4 to sum.exe...\n");
    fprintf (f, "%d\n%d\n", 3, 4);

    pclose (f);
    return 0;
}