Capturing syscall stdout without writing to file i

2019-01-20 17:48发布

I want to read the std output of a system call into a C/C++ string. Can I do this without using a temp file?

Perl

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

C++

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

2条回答
Bombasti
2楼-- · 2019-01-20 18:12

This might help you redirect stdout from a system call.

查看更多
Evening l夕情丶
3楼-- · 2019-01-20 18:26

Using C's popen (probably the simplest solution, even if it doesn't use C++'s 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);

Assuming your iostream has the non-standard xfstream::xfstream(int fd) constructor:

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

Using Boost.Iostreams, you don't have to depend upon non-standard extensions to iostream:

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

Unfortunately, Windows is horrible and _popen only works for console applications; for a graphical app:

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

(completely untested)

查看更多
登录 后发表回答