cpp-zlib-string-compress-uncompress

#include <iostream> #include <cstring> #include <zlib.h> #define CHUNK_SIZE 16384 int compressString(const std::string& inputString, std::string& compressedString) { z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK) { return -1; } size_t inputOffset = 0; size_t outputOffset = 0; compressedString.resize(inputString.size() + 128); while (inputOffset < inputString.size()) { stream.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(&inputString[inputOffset])); stream.avail_in = static_cast<uInt>(std::min(CHUNK_SIZE, inputString.size() - inputOffset)); stream.next_out = reinterpret_cast<unsigned char*>(&compressedString[outputOffset]); stream.avail_out = static_cast<uInt>(compressedString.size() - outputOffset); int result = deflate(&stream, Z_FINISH); if (result == Z_STREAM_ERROR) { return -1; } outputOffset = stream.total_out; inputOffset += CHUNK_SIZE; compressedString.resize(outputOffset + CHUNK_SIZE); } if (deflateEnd(&stream) != Z_OK) { return -1; } compressedString.resize(outputOffset); return 0; } int decompressString(const std::string& compressedString, std::string& decompressedString) { z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; if (inflateInit(&stream) != Z_OK) { return -1; } size_t inputOffset = 0; size_t outputOffset = 0; decompressedString.resize(compressedString.size() * 2); while (inputOffset < compressedString.size()) { stream.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(&compressedString[inputOffset])); stream.avail_in = static_cast<uInt>(std::min(CHUNK_SIZE, compressedString.size() - inputOffset)); stream.next_out = reinterpret_cast<unsigned char*>(&decompressedString[outputOffset]); stream.avail_out = static_cast<uInt>(decompressedString.size() - outputOffset); int result = inflate(&stream, Z_FINISH); if (result == Z_STREAM_ERROR) { return -1; } outputOffset = stream.total_out; inputOffset += CHUNK_SIZE; decompressedString.resize(outputOffset + CHUNK_SIZE); } if (inflateEnd(&stream) != Z_OK) { return -1; } decompressedString.resize(outputOffset); return 0; } int main() { std::string inputString = "Hello, world!"; std::string compressedString; if (compressString(inputString, compressedString) != 0) { std::cerr << "Error compressing string" << std::endl; return -1; } std::cout << "Compressed string size: " << compressedString.size() << std::endl; std::string decompressedString; if (decompressString(compressedString, decompressedString) != 0) { std::cerr << "Error decompressing string" << std::endl; return -1; } std::cout << "Decompressed string: " << decompressedString << std::endl; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章