简体   繁体   English

从c ++ system()命令捕获缓冲区输出

[英]capture buffer output from a c++ system() command

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++? 我如何捕获我在命令行运行的php脚本的输出并将其存储到c ++中的数组? ie

system('php api/getSome.php');

system can't give output to your program. system无法为您的程序提供输出。 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 . 你应该将命令输出重定向到一个文件,比如在php api/getSome.php > somefile并从你的程序中读取这个文件,或者你应该使用一个能够为你提供命令输出的正确函数,比如popen

from the man page: 从手册页:

system() executes a command specified in command by calling /bin/sh -c command. system()通过调用/ bin / sh -c命令执行命令中指定的命令。

Just use the shell redirection facility to dump the output of the command in a file: 只需使用shell重定向工具将命令的输出转储到文件中:

 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 . 上面将给出output.txt中的标准输出和error.txt中的错误输出。

Traditionally popen() is preferred when you need to IO between your parent and child process. 传统上,当您需要在父进程和子进程之间进行IO时,首选popen()。 It uses the C based FILE stream. 它使用基于C的FILE流。 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. 它是同一个低级内在函数的包装器,也构成了system(),即fork + execl,但与system()不同,popen()打开一个管道并将stdin / out复制到一个流中进行读写。

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

Then read from it like a file. 然后从文件中读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM