std::cout << system("my cmd"); 将打印来自std::system(这是一个int)的返回值,而不是来自您在system("my_cmd"); 中执行的命令的stdout。在 C++ 中没有捕获外部命令输出的标准方法。
我建议安装boost 库(如果尚未安装)并使用boost::process,这样可以轻松完成。
同步示例:
#include "boost/process.hpp"
#include <iostream>
#include <string>
namespace bp = boost::process;
int main() {
// Use boost's pipes to capture the output:
// https://www.boost.org/doc/libs/release/doc/html/boost/process/basic_ipstream.html
bp::ipstream out;
bp::ipstream err;
// boost's version of system() has poor documentation. Read the
// tutorial in the top link instead.
bp::system("/usr/bin/ls", "-m", "non-existing", "/dev",
bp::std_out > out, bp::std_err > err, bp::std_in < stdin);
// note how you can redirect stdout, stderr and even stdin to/from boost's ipstream's
// Now you can read from the ipstreams with std::getline, just like any
// other istream:
std::string line;
std::cout << "stdout capture:\n";
while(std::getline(out, line)) {
std::cout << line << '\n';
}
std::cout << "\nstderr capture:\n";
while(std::getline(err, line)) {
std::cout << line << '\n';
}
}
可能的输出:
stdout capture:
/dev:
autofs, block, bsg, btrfs-control, bus, cdrom, char, console, core, cpu,
cpu_dma_latency, disk, dma_heap, dri, fb0, fd, full, fuse, gpmctl, hidraw0,
hidraw1, hidraw2, hidraw3, hidraw4, hidraw5, hidraw6, hpet, hugepages, hwrng,
initctl, input, ipmi0, kmsg, kvm, log, loop0, loop-control, lp0, lp1, lp2, lp3,
mapper, mcelog, megaraid_sas_ioctl_node, mem, mqueue, net, null, nvram, port,
ppp, ptmx, ptp0, ptp1, pts, random, raw, rfkill, rtc, rtc0, sda, sda1, sda2,
sda3, sda4, sg0, sg1, shm, snapshot, snd, sr0, stderr, stdin, stdout, tty, tty0,
tty1, tty10, tty11, tty12, tty13, tty14, tty15, tty16, tty17, tty18, tty19,
tty2, tty20, tty21, tty22, tty23, tty24, tty25, tty26, tty27, tty28, tty29,
tty3, tty30, tty31, tty32, tty33, tty34, tty35, tty36, tty37, tty38, tty39,
tty4, tty40, tty41, tty42, tty43, tty44, tty45, tty46, tty47, tty48, tty49,
tty5, tty50, tty51, tty52, tty53, tty54, tty55, tty56, tty57, tty58, tty59,
tty6, tty60, tty61, tty62, tty63, tty7, tty8, tty9, ttyS0, ttyS1, ttyS10,
ttyS11, ttyS12, ttyS13, ttyS14, ttyS15, ttyS16, ttyS17, ttyS18, ttyS19, ttyS2,
ttyS20, ttyS21, ttyS22, ttyS23, ttyS24, ttyS25, ttyS26, ttyS27, ttyS28, ttyS29,
ttyS3, ttyS30, ttyS31, ttyS4, ttyS5, ttyS6, ttyS7, ttyS8, ttyS9, udmabuf, uhid,
uinput, urandom, usb, usbmon0, usbmon1, usbmon2, vcs, vcs1, vcs2, vcs3, vcs4,
vcs5, vcs6, vcsa, vcsa1, vcsa2, vcsa3, vcsa4, vcsa5, vcsa6, vcsu, vcsu1, vcsu2,
vcsu3, vcsu4, vcsu5, vcsu6, vfio, vga_arbiter, vhci, vhost-net, vhost-vsock,
watchdog, watchdog0, zero
stderr capture:
/usr/bin/ls: cannot access 'non-existing': No such file or directory