2017-04-23 24 views
1

我正在使用filetering_istream类型将信息保存在解压缩文件中,同时使用'boost/iostreams/filtering_stream.hpp'。但是我想把它转换成ifstream类型。有没有办法做到这一点?万分感谢!将iframestream类型的filtering_istream类型的变量投入?

的代码如下:

#include <istream> 
#include <fstream> 
#include <boost/iostreams/filtering_stream.hpp> 
#include <boost/iostreams/filter/gzip.hpp> 

int main(){  
    std::ifstream file("test_data.dat.gz"); 

    boost::iostreams::filtering_istream in; 

    in.push(boost::iostreams::gzip_decompressor()); 

    in.push(file); 

    /* add code to convert filtering_istream 'in' into ifstream 'pfile' */ 

    /* It seems that the following code returns a pointer NULL */ 

    // std::ifstream* pfile = in.component<std::ifstream>(1); 

    return 0; 

} 

努力的boost ::裁判和boost ::通过zett42提出的包装后,ifstream的确实有效。唯一的问题是它没有给出想要的短语。

在我的.gz文件的文本,我写道:

THIS IS A DATA FILE! 
8 plus 8 is 16 

但使用ifstream的,我得到:

is_open: 1 

\213<\373Xtest_data.dat\361\360V"G\307G7OWE.\205\202\234\322b\205\314bC3.\327+>\314$

我不知道这里发生了什么,我能做点什么来恢复它吗?

+0

如果您使用'ifstream',您将读取* compressed *数据。也许我完全误解了你的问题。如果你想读取未压缩的数据,你只需从'in'中读取。那么不需要“施放”任何东西。 – zett42

回答

0

filtering_stream参考:

filtering_stream从标准:: basic_istream,性病:: basic_ostream 或std :: basic_iostream导出,这取决于它的模式参数。

所以不,你不能将filtering_stream直接投到ifstream因为两者之间没有继承关系。

如果您的过滤器链以ifstream的设备结束,您可以改为执行filtering_stream::component()以抓取该设备。对于流,这个函数返回一个boost::iostreams::detail::mode_adapter(你可以通过调用in.component_type(1)来看到这个类型)。

依靠内部增强类型(由命名空间“细节”表示)可能会改变下一个增强版本,所以一个解决方法是使用boost::reference_wrapper代替,这可能不是一个好主意。

#include <iostream> 
#include <istream> 
#include <fstream> 
#include <boost/iostreams/filtering_stream.hpp> 
#include <boost/iostreams/filter/gzip.hpp> 
#include <boost/core/ref.hpp> 

int main(){  
    std::ifstream file("test_data.dat.gz"); 

    boost::iostreams::filtering_istream in; 

    in.push(boost::iostreams::gzip_decompressor()); 

    in.push(boost::ref(file)); 

    if(auto pfile = in.component<boost::reference_wrapper<std::ifstream>>(1)) 
    { 
     std::ifstream& rfile = *pfile; 
     std::cout << "is_open: " << rfile.is_open() << "\n"; 
    } 
} 
+0

Thx对于这种灵感,但似乎pfile是一个NULL指针,如果我想打印内部的内容导致分段错误。你有这个想法吗?我确定'in'是正确的,因为我可以使用getline函数输出内部的内容。伟大的thx! – hyoukai

+0

@hyoukai你能给你的问题添加一个代码示例吗? – zett42

+0

Thx为您的关注。代码已添加。伟大的thx,如果你能给我一些想法! – hyoukai