温馨提示×

C++中gzip压缩的示例代码有哪些

c++
小樊
99
2024-08-11 11:41:36
栏目: 编程语言

  1. 使用zlib库进行gzip压缩的示例代码:
#include <iostream>
#include <zlib.h>

int main() {
    const char *input_data = "Hello, World!";
    uLong input_size = strlen(input_data) + 1;

    uLong output_size = compressBound(input_size);
    Bytef* output_data = new Bytef[output_size];

    compress(output_data, &output_size, (Bytef*)input_data, input_size);

    std::cout << "Compressed data: ";
    for (uLong i = 0; i < output_size; i++) {
        std::cout << output_data[i];
    }

    delete[] output_data;

    return 0;
}
  1. 使用Boost库进行gzip压缩的示例代码:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>

int main() {
    std::string input_data = "Hello, World!";

    std::stringstream compressed_data;
    boost::iostreams::filtering_ostream out;
    out.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(boost::iostreams::gzip::best_compression)));
    out.push(compressed_data);

    out << input_data;
    out.pop();

    std::cout << "Compressed data: " << compressed_data.str() << std::endl;

    return 0;
}

这两个示例代码分别使用zlib库和Boost库实现了gzip压缩。可以根据实际需求选择合适的库进行使用。

0