我想将系统调用的 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;
我想将系统调用的 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::
xfstream(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]);
(完全未经测试)
这可能会帮助您从系统调用重定向标准输出。