简体   繁体   中英

Write gzipped file using gzip

There is a function which takes FILE* to serialize the object.

In addition I want to serialize object in gzip format.

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. So you need to test for null from popen before you construct the shared_ptr.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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