捕获系统调用标准输出,而无需编写的C / C到文件++ [英] Capturing syscall stdout without writing to file in C/C++

查看:143
本文介绍了捕获系统调用标准输出,而无需编写的C / C到文件++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读一个系统调用的输出性病成C / C ++字符串。我可以做到这一点不使用临时文件?

Perl的

  //没有文件IO
$输出=`回声hello`;

C ++

  //使用文件IO
系统(回声你好> TMP);
性病:: fstream的文件(TMP);
性病::字符串s;
文件>> S;


解决方案

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

  FILE * p =的popen(回声你好,R);
性病::字符串s;
用于(为size_t计数(计数= FREAD(BUF,1,sizeof的(BUF),P));)
    S + =字符串(BUF,BUF +计数);
pclose函数(对);

假设你的的iostream 有非标准的 X fstream的: X 的fstream(INT FD)构造器:

  FILE * p =的popen(回声你好,R);
性病:: ifstream的P2(的fileno(P));
性病::字符串s;
P2>> S;
p2.close();
pclose函数(对);

使用了Boost.Iostreams ,则不必依赖于非标准扩展到的iostream

 的boost ::输入输出流:: file_descriptor_source P2(的fileno(P));

不幸的是,Windows是可怕的, _popen 仅适用于控制台应用程序;对于图形应用程序:

  SECURITY_ATTRIBUTES秒;
sec.nLength = sizeof的(秒);
sec.bInheritHandle = TRUE;
sec.lpSecurityDescriptor = NULL;
HANDLE * H [2];
CreatePipe(安培; H [0],&放大器; H [1],&放大器;秒,0);
SetHandleInformation(H [0],HANDLE_FLAG_INHERIT,0)
STARTUPINFO SI;
memset的((无效*)及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 \\回声你好\\,NULL,NULL,TRUE,0,NULL,NULL,&放大器; SI,NULL);
提高::输入输出流:: file_descriptor_source P(H [0]);

(完全未经测试)

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;

解决方案

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)

这篇关于捕获系统调用标准输出,而无需编写的C / C到文件++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆