C++中g(shù)zip壓縮的示例代碼有哪些

c++
小樊
102
2024-08-11 11:41:36

  1. 使用zlib庫(kù)進(jìn)行g(shù)zip壓縮的示例代碼:
#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庫(kù)進(jìn)行g(shù)zip壓縮的示例代碼:
#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;
}

這兩個(gè)示例代碼分別使用zlib庫(kù)和Boost庫(kù)實(shí)現(xiàn)了gzip壓縮??梢愿鶕?jù)實(shí)際需求選擇合適的庫(kù)進(jìn)行使用。

0