我想压缩我的程序(在 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/