ITeye博客

C++中读取控制台输出,并将文件指针FILE*转换为istream

cherishLC · 2017-11-27 15:03 · C++ · 编程语言 · C++ · Markdown

解决的问题: [list] [*]1、通过执行系统的bash命令后,获取其输出(类似python的subprocess模块) [*]2、将输出从FILE*转换为std::istream,方便按照C++的方式进行处理 [/list] 获取bash命令的输出:[url]http://www.cnblogs.com/caosiyang/archive/2012/06/25/2560976.html[/url] 将文件指针FILE*转换为istream:[url]https://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor[/url] 本文采用以上问题中Mark给的方案(貌似boost库中用的也是该方案),即重新定义了一个buffer类,参见以下链接中的fdinbuf类及其在fdistream中的使用方式:[url]http://www.josuttis.com/cppcode/fdstream.html[/url] 示例代码(完整程序见附件): [code="c++"]#include #include #include #include #include #include #include "fdstream.hpp" //using namespace std; using std::string; std::shared_ptr eg_read_from_bash_output(const char *cmd) { ::FILE *fp = ::popen(cmd, "r"); if (!fp) { throw string("count not open PIPE"); } //boost::fdistream fs(fileno(fp)); //注意因为父类istream没有 operator =, 不能够将改类作为返回值。 //如需将fs作为返回值,需使用std::shared_ptr进行封装: http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr std::shared_ptr pfi(new boost::fdistream(fileno(fp))); return pfi; } int main(){ auto pfi = eg_read_from_bash_output("cat hello.txt"); boost::fdistream& fs = *pfi; string line; while (std::getline(fs, line)) { std::cout << line << std::endl; } }[/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。