使用gzip

时间:2015-07-08 08:11:12

标签: c++ pipe

有一个函数需要FILE*来序列化对象。

另外我想以gzip格式序列化对象。

要做到这一点,我试试这个:

   boost::shared_ptr<FILE>
    openForWriting(const std::string& fileName)
    {
        boost::shared_ptr<FILE> f(popen(("gzip > " + fileName).c_str(), "wb"), pclose);
        return f;
    }

    boost::shared_ptr<FILE> f = openForWriting(path);
    serilizeUsingFILE(f.get());

但这种做法导致了段错误。

你能帮我理解段错误的原因吗?

1 个答案:

答案 0 :(得分:2)

你有几个问题。

首先,如果你传递NULL,pclose会发生段错误。因此,在构造shared_ptr之前,需要从popen测试null。

其次,popen不会将'b'作为标志,因此类型字符串应该只是“w”。

boost::shared_ptr<FILE> 
    openForWriting(const std::string& fileName) 
    { 
        FILE *g = popen(("gzip >" + fileName).c_str(), "w"); 
        if (!g) 
            return boost::shared_ptr<FILE>(); 
        boost::shared_ptr<FILE> f(g, pclose); 
        return f; 
    }