`

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

    博客分类:
  • C++
阅读更多
解决的问题:
  • 1、通过执行系统的bash命令后,获取其输出(类似python的subprocess模块)
  • 2、将输出从FILE*转换为std::istream,方便按照C++的方式进行处理



获取bash命令的输出:http://www.cnblogs.com/caosiyang/archive/2012/06/25/2560976.html

将文件指针FILE*转换为istream:https://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor

本文采用以上问题中Mark给的方案(貌似boost库中用的也是该方案),即重新定义了一个buffer类,参见以下链接中的fdinbuf类及其在fdistream中的使用方式:http://www.josuttis.com/cppcode/fdstream.html


示例代码(完整程序见附件):
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdio.h>
#include <string>
#include <memory>
#include "fdstream.hpp"

//using namespace std;
using std::string;

std::shared_ptr<boost::fdistream> 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<boost::fdistream> 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;
	}
	
}

分享到:
评论

相关推荐

    C++文件操作 C++ 文件操作

    这段代码将读取 `example.txt` 文件中的内容并打印到控制台。 #### 五、文件位置指针操作 `ifstream` 和 `ofstream` 都包含了一个输入位置指针(`getpointer`)和输出位置指针(`putpointer`)。对于 `fstream` 和...

    C++primer中文版第四版习题答案第八章归纳.pdf

    这个函数将读取的内容输出到标准输出(通常是控制台),并在读取过程中处理可能出现的错误。如果遇到文件结束符,流会被重置以便后续使用。 6. **测试函数的调用**: 要通过`cin`调用这个函数,可以直接在`main`...

    C++文件读写详解

    C++中的文件读写是程序设计中不可或缺的一部分,它允许我们保存数据到磁盘以便后续使用或读取已存在的数据。在C++中,我们主要使用三个类来处理文件操作:ofstream、ifstream和fstream。 ofstream类是用于写操作,...

    11-12程序设计及算法语言Ⅱ上级考试试卷A(电类).doc

    链表类还需要重载流操作符`和`&gt;&gt;`,以实现从文件读取链表数据和向控制台输出链表内容。 7. **文件操作**:在C++中,文件操作通常通过`fstream`类完成。`file.open()`用于打开文件,`file.close()`关闭文件,`file....

    C++课程设计

    - `ostream& operator(ostream& out, Staff& a)`:重载`运算符,使得可以将`Staff`对象的数据输出到输出流中。 4. **异常处理**: - 文件操作可能出现失败的情况,例如文件不存在或权限问题等,可以通过条件判断...

    11-12程序设计及算法语言Ⅱ上级考试试卷B(电类).doc

    - 文件 `ListB.txt` 用于存储链表的数据,通过重载的 `&gt;&gt;` 操作符从文件读取数据到链表,`操作符则将链表数据输出到控制台。 - 考生需要完成链表类的相关方法,确保数据能正确地从文件读取到链表,以及从链表输出...

    The-C++-Programming-Language(ch 3)

    C++的标准库提供了一系列输出流操作符(如`),这些操作符可以用来输出数据到控制台或其他输出设备。例如,可以使用`cout`来打印字符串或数值: ```cpp #include using namespace std; int main() { cout , ...

Global site tag (gtag.js) - Google Analytics