I have some data that I want to format and output, either in raw text file or .gz compressed text file.
Thus, I wanted to do something like this :
shared_ptr<ofstream> file = make_shared<ofstream>(filename.c_str());
shared_ptr<ostream> stream;
if (compressed) {
stream = getCompressedStream(*file);
} else {
stream = std::move(file);
}
for (auto c = data.begin(); c != data.end(); ++c) {
*stream << **c << "\t" << (*c)->getThing() << endl;
}
With getCompressedStream a function that decrypt the stream and return a new non encrypted stream :
std::unique_ptr<std::ostream> getCompressedStream(std::ofstream& file)
{
typedef io::filtering_ostream filter;
std::unique_ptr<filter> out = std::unique_ptr<filter> (new filter());
out->push(io::gzip_compressor());
out->push(file);
return std::move(out);
}
So I wanted getCompressedStream to abstract calls to boost lib, so that I only use std streams in my main program.
It's not working : the .gz file is damaged/not readable.
According to this thread, the output of a filtering_stream is done in the destruction of the object. Thus, I don't know if it can be done cleanly with shared_ptr. I don't know whether file or stream is destroyed first, and I guess this leads to issues.
Do you think implementing getCompressedStream this way is possible? What would you change?
Thanks
Edit : It works if I switch to regular pointers instead of shared pointers, and delete the stream explicitely before the file.