您好,我想使用Boost.IOstreams将数据存储到bzip2文件中。

void test_bzip()
{
namespace BI = boost::iostreams;
{
string fname="test.bz2";
  {
    BI::filtering_stream<BI::bidirectional> my_filter;
    my_filter.push(BI::combine(BI::bzip2_decompressor(), BI::bzip2_compressor())) ;
    my_filter.push(std::fstream(fname.c_str(), std::ios::binary|std::ios::out)) ;
    my_filter << "test" ;

    }//when my_filter is destroyed it is trowing an assertion.
}
};

我做错了什么?
我正在使用Boost 1.42.0。

亲切的问候
阿曼

编辑
如果我删除了双向选项,代码将正常工作:
#include <fstream>
#include <iostream>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <string>



void test_bzip()
{
        namespace BI = boost::iostreams;
        {
                std::string fname="test.bz2";
                {
                        std::fstream myfile(fname.c_str(), std::ios::binary|std::ios::out);
                        BI::filtering_stream<BI::output> my_filter;
                        my_filter.push(BI::bzip2_compressor()) ;
                        //my_filter.push(std::fstream(fname.c_str(), std::ios::binary|std::ios::out)) ; //this line will work on VC++ 2008 V9 but not in G++ 4.4.4
                        my_filter.push(myfile);
                        my_filter << "test";
                }
        }
};

也许有人可以解释为什么?

最佳答案

fstream无法复制,因此您必须使用push的引用版本

template<typename StreamOrStreambuf>
void push( StreamOrStreambuf& t,
           std::streamsize buffer_size = default value,
           std::streamsize pback_size = default value );

所以你的功能应该看起来像
std::fstream theFile(fname.c_str(), std::ios::binary | std::ios::out);
// [...]
my_filter.push(theFile) ;

我很惊讶您的编译器允许您的代码,我认为它提示引用了临时...您使用的是哪个编译器?

关于c++ - BOOST.IOstreams : trouble to write to bzip2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2559225/

10-11 22:08
查看更多