簡體   English   中英

使用gzip寫入壓縮文件

[英]Write gzipped file using gzip

有一個函數使用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());

但是這種方法導致了段錯誤。

您能幫我了解段錯誤的原因嗎?

你有幾個問題。

首先,如果將pclose傳遞為NULL,它將關閉segfault。 因此,在構造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; 
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM