21

Okay so my question is this. Say I have a simple C++ code:

#include <iostream>
using namespace std;

int main(){
   cout << "Hello World" << endl;
   return 0;
}

Now say I have this program that I would like to run in my program, call it prog. Running this in the terminal could be done by:

./prog

Is there a way to just do this from my simple C++ program? For instance

#include <iostream>
using namespace std;

int main(){
   ./prog ??
   cout << "Hello World" << endl;
   return 0;
}

Any feedback would be very much obliged.

Steve Fallows
  • 6,274
  • 5
  • 47
  • 67
Vincent Russo
  • 1,087
  • 3
  • 20
  • 33
  • 1
    possible duplicate of http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c – hopia Feb 02 '12 at 21:57
  • 1
    @hopia, not a duplicate. What you pointed to is a question about advanced uses of `system()`; this poster just needed to know about the function’s existence. – J. C. Salomon Feb 02 '12 at 22:04

5 Answers5

24

You want the system() library call; see system(3). For example:

#include <cstdlib>

int main() {
   std::system("./prog");
   return 0;
}

The exact command string will be system-dependent, of course.

J. C. Salomon
  • 4,143
  • 2
  • 29
  • 38
9

You can also use popen

#include <stdio.h>

int main(void)
{
        FILE *handle = popen("./prog", "r");

        if (handle == NULL) {
                return 1;
        }

        char buf[64];
        size_t readn;
        while ((readn = fread(buf, 1, sizeof(buf), handle)) > 0) {
                fwrite(buf, 1, readn, stdout);
        }

        pclose(handle);

        return 0;
}
xda1001
  • 2,449
  • 16
  • 18
5

You could us the system command:

system("./prog");
elimirks
  • 1,452
  • 2
  • 17
  • 30
4

Try system(3) :

system("./prog");
James M
  • 18,506
  • 3
  • 48
  • 56
2

You could use a system call like this: http://www.cplusplus.com/reference/clibrary/cstdlib/system/

Careful if you use user input as a parameter, its a good way to have some unintended consequences. Scrub everything!

Generally, system calls can be construed as bad form.

gmoney
  • 1,264
  • 1
  • 10
  • 12