I’m trying using pipes with boost libraries, I just want to execute a background program(e.g.: ls) and get it’s output in a string(like you can do with fopen and fread), but I really can’t get why I have no output with this code:
#include <iostream>
#include <cstdio>
#include <sstream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
int
main(int argc, char** argv)
{
using namespace boost::iostreams;
if(argc < 2) {
return -1;
}
FILE* p = popen(argv[1], "r");
if(! p) {
std::cerr << "error open pipe" << std::endl;
return -2;
}
int fd = fileno(p);
std::stringstream ss;
ss << fd;
std::string s = ss.str();
file_descriptor_source pdesc(s);
stream_buffer<file_descriptor_source> pstream(pdesc);
std::istream is(&pstream);
std::string out;
while(is) {
std::getline(is, out);
std::cout << out << std::endl;
}
pstream.close();
pdesc.close();
pclose(p);
return 0;
}
Thanks in advance.
It seems you are trying to open a
boost::file_descriptor_sourcefrom a “path” which contains the file descriptor number. However, a file of this name probably doesn’t exist. What you probably meant to use is something like this: