- 1. After executing the bash command of the system, get its output (similar to python's subprocess module)
- 2. Convert the output from FILE* to std::istream, which is convenient for processing in the way of C++
Get the output of the bash command: http://www.cnblogs.com/caosiyang/archive/2012/06/25/2560976.html
Convert the file pointer FILE* to istream: https://stackoverflow.com/questions/2746168/ how-to-construct-ac-fstream-from-a-posix-file-descriptor
This article adopts the scheme given by Mark in the above question (it seems that the scheme is also used in the boost library), that is, redefines a buffer class, see the following The fdinbuf class in the link and how it is used in fdistream: http://www.josuttis.com/cppcode/fdstream.html
Sample code (see attachment for complete program):
#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)); //Note that because the parent class istream does not have operator =, the changed class cannot be used as the return value. //To use fs as the return value, use std::shared_ptr to encapsulate: 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; } }