我想将系统调用的标准输出读入C / C++字符串。我可以在不使用临时文件的情况下执行此操作吗?

佩尔

//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]);

(未经测试)

关于c++ - 在不写入C/C++文件的情况下捕获syscall stdout,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1103047/

10-12 21:34