1

How would I capture the output from a php script that I run at the command line and store it to an array in c++? i.e.

system('php api/getSome.php');
  • possible duplicate of [How can I run an external program from C and parse its output?](http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output) – Mahesh Bansod Oct 31 '14 at 07:21

3 Answers3

1

system can't give output to your program. You should redirect the command output to a file, like in php api/getSome.php > somefile and read this file from your program, or you should use a proper function that can give you the command output, like popen.

oblitum
  • 11,380
  • 6
  • 54
  • 120
  • In this particular case, I would really like to capture it in memory first for a string match. Speed is a big deal here. The fewer processes to get the string, the better. –  Oct 31 '14 at 15:14
1

from the man page:

system() executes a command specified in command by calling /bin/sh -c command.

Just use the shell redirection facility to dump the output of the command in a file:

 system("php api/getSome.php > output.txt 2> error.txt");

The above will give send the standard output in output.txt and the error output in error.txt.

didierc
  • 14,572
  • 3
  • 32
  • 52
1

Traditionally popen() is preferred when you need to IO between your parent and child process. It uses the C based FILE stream. It is a wrapper around the same low level intrinsics that also make up system(), namely fork + execl, but unlike system(), popen() opens a pipe and dups stdin/out to a stream for reading and writing.

FILE *p = popen("ping www.google.com", "r");

Then read from it like a file.

codenheim
  • 20,467
  • 1
  • 59
  • 80