c++ - 文件压缩以处理 C++ 中的中间输出

标签 c++

我想压缩我的程序(在 C++ 中)的中间输出,然后解压缩它。

最佳答案

您可以使用 Boost IOStreams 来压缩您的数据,例如,沿着这些行压缩/解压缩到文件中/从文件中解压缩(示例改编自 Boost docs):

#include <fstream>
#include <iostream>

#include <boost/iostreams/filtering_stream.hpp>    
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

namespace bo = boost::iostreams;

int main() 
{
    {
    std::ofstream ofile("hello.gz", std::ios_base::out | std::ios_base::binary);
    bo::filtering_ostream out;
    out.push(bo::gzip_compressor()); 
    out.push(ofile); 
    out << "This is a gz file\n";
    }

    {
    std::ifstream ifile("hello.gz", std::ios_base::in | std::ios_base::binary);
    bo::filtering_streambuf<bo::input> in;
    in.push(bo::gzip_decompressor());
    in.push(ifile);
    boost::iostreams::copy(in, std::cout);
    }
}

您还可以查看 Boost Serialization - 它可以让您更轻松地保存数据。可以结合这两种方法 ( example )。 IOStreams 也支持 bzip 压缩。

编辑:为了解决您最后的评论 - 您可以压缩现有文件......但最好将其写成压缩文件。如果您确实需要,可以调整以下代码:

std::ifstream ifile("file", std::ios_base::in | std::ios_base::binary);
std::ofstream ofile("file.gz", std::ios_base::out | std::ios_base::binary);

bo::filtering_streambuf<bo::output> out;
out.push(bo::gzip_compressor());
out.push(ofile); 
bo::copy(ifile, out);

关于c++ - 文件压缩以处理 C++ 中的中间输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156172/

相关文章:

c++ - 数独解算器由于某种原因不断卡住

c++ - std::allocator 中的直接初始化与统一初始化

c++ - 如何在 wchar_t* 和 int 之间转换?

C++ 在映射中存储变体类型

c++ - 大数求和

c++ - '(QMessageBox::Icon)1u' 不能用作函数

c++ - directx C++ 第一人称相机

c++ - std::is_signed<T> 和 std::numeric_limits<T>::is_signed 之间的区别?

c++ - file_not_found 错误 - 带有 Visual Studio 2015 的 directx 工具包

c++ - 如何在其他两个之间设置工具栏