capture buffer output from a c++ system() command

感情迁移 提交于 2021-02-05 09:19:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!