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

前端 未结 5 1064
自闭症患者
自闭症患者 2021-01-12 20:58

Say i have an exe, lets say sum.exe. Now say the code for sum.exe is

void main ()
{
 int a,b;
 scanf (\"%d%d\", &a, &b);
 printf (\"%d\", a+b);
}
         


        
5条回答
  •  野的像风
    2021-01-12 21:40

    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 
    #include 
    
    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;
    }
    

提交回复
热议问题