---
title: "C++中读取控制台输出，并将文件指针FILE*转换为istream"
author: "cherishLC"
date: "2017-11-27T15:03:45Z"
tags: ["C++"]
categories: ["编程语言"]
slug: "c-file-istream"
draft: false
lastmod: "2017-11-27T14:57:28Z"
id: 2400974
url: "https://cherishlc.iteye.com/blog/2400974"
---

解决的问题： \[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 &lt;&lt; line &lt;&lt; std::endl; } }\[/code]