简体   繁体   English

使用gzip写入压缩文件

[英]Write gzipped file using gzip

There is a function which takes FILE* to serialize the object. 有一个函数使用FILE*来序列化对象。

In addition I want to serialize object in gzip format. 另外,我想以gzip格式序列化对象。

To do this I have try this: 为此,我尝试这样做:

   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());

But this approach results to segfault. 但是这种方法导致了段错误。

Can you please help me to understand the cause of segfault? 您能帮我了解段错误的原因吗?

You have a couple of problems. 你有几个问题。

Firstly, pclose will segfault if you pass it NULL. 首先,如果将pclose传递为NULL,它将关闭segfault。 So you need to test for null from popen before you construct the shared_ptr. 因此,在构造shared_ptr之前,需要测试popen中的null。

Secondly, popen doesn't take 'b' as a flag, so the type string should just be "w". 其次,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; 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM