graw graw - 1 month ago 19
C++ Question

istream from file_descriptor_source (boost::iostreams) or file

I need to do something like this for my program's input:

stream input;
if (decompressed)
input.open(filepath);
else {
file_descriptor=_popen("decompressor "+filepath,"r");
input.open(file_descriptor);
}
input.read(...)
...


I can see one solution - to use _popen in both cases and just copy the file to stdout if it's already decompressed, but this doesn't seem very elegant.

Funny how difficult this is compared with C - I guess the standard library missed it. Now I am lost in the cryptic boost::iostreams documentation. Example code would be great if anyone knows how.

Answer

Is this what you're after:

#include <cstdio>
#include <string>
#include <iostream>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    bool flag = false;

    FILE* handle = 0; 
    if (flag)
    {
        handle = _popen("dir", "r");
    }
    else
    {
        handle = fopen ("main.cpp", "r");
    }

    io::stream_buffer<io::file_descriptor_source> fpstream (fileno(handle));
    std::istream in (&fpstream);

    std::string line;
    while (in)
    {
        std::getline (in, line);
        std::cout << line << std::endl;
    }

    return 0;
}
Comments