捕获系统调用标准输出而无需在C / C ++中写入文件

我想将系统调用的std输出读入C / C ++字符串。 我可以不使用临时文件吗?

Perl的

//without file io $output = `echo hello`; 

C ++

 //with file io system ("echo hello > tmp"); std::fstream file ("tmp"); std::string s; file >> s; 

使用C的popen (可能是最简单的解决方案,即使它不使用C ++的iostream ):

 FILE *p = popen("echo hello", "r"); std::string s; for (size_t count; (count = fread(buf, 1, sizeof(buf), p));) s += string(buf, buf + count); pclose(p); 

假设你的iostream有非标准的x fstream:: x fstream(int fd)构造函数:

 FILE *p = popen("echo hello", "r"); std::ifstream p2(fileno(p)); std::string s; p2 >> s; p2.close(); pclose(p); 

使用Boost.Iostreams ,您不必依赖于iostream的非标准扩展:

 boost::iostreams::file_descriptor_source p2(fileno(p)); 

不幸的是,Windows非常糟糕, _popen仅适用于控制台应用程序; 对于图形应用程序:

 SECURITY_ATTRIBUTES sec; sec.nLength = sizeof(sec); sec.bInheritHandle = TRUE; sec.lpSecurityDescriptor = NULL; HANDLE *h[2]; CreatePipe(&h[0], &h[1], &sec, 0); SetHandleInformation(h[0], HANDLE_FLAG_INHERIT, 0) STARTUPINFO si; memset((void *)&si, 0, sizeof(si)); si.hStdInput = INVALID_HANDLE_VALUE; si.hStdOutput = h[1]; si.hStdError = INVALUD_HANDLE_VALUE; si.dwFlags |= STARTF_USESTDHANDLES; CreateProcess(NULL, "cmd /c \"echo hello\"", NULL, NULL, TRUE, 0, NULL, NULL, &si, NULL); boost::iostreams::file_descriptor_source p(h[0]); 

(完全未经测试)

这可能有助于您从系统调用重定向stdout。