问题
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');
回答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.
回答2:
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
.
回答3:
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.
来源:https://stackoverflow.com/questions/26668942/capture-buffer-output-from-a-c-system-command