Qt使用一些壓縮解壓功能,介紹過libzip庫編譯,本篇說明zlib庫。緩存
zlib被設計爲一個免費的,通用的,法律上不受限制的-即不受任何專利保護的無損數據壓縮庫,幾乎能夠在任何計算機硬件和操做系統上使用。
官網:http://www.zlib.net/
CSDN下載地址:https://download.csdn.net/download/qq21497936/13944558
QQ羣:1047134658(點擊「文件」搜索「zlip」,羣內與博文同步更新)app
void ZlibManager::testEnv() { QString fileName = "1.txt"; QString outFileName = "1.txt_zip"; // 打開文件,讀取進入內存 QFile file(fileName); if(!file.open(QIODevice::ReadOnly)) { LOG; return; } QByteArray byteArray = file.readAll(); LOG << byteArray.size(); byteArray.append((char)0x00); LOG << "origin size:" << byteArray.size() << ":" << QString(byteArray); file.close(); // 計算壓縮後的文件大小 int len = compressBound(byteArray.size()); LOG << len << (uLong)byteArray.size(); QByteArray compressByteArray = QByteArray(len, 0x00); int ret = compress((uchar *)compressByteArray.data(), (uLong *)&len, (uchar *)byteArray.data(), (uLong)byteArray.size()); LOG << ret << len; if(Z_OK == ret) { LOG << "Succeed to compress" << byteArray.size() << "to" << len; } // 壓縮後存入文件 QFile outFile(outFileName); if(!outFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { LOG; return; } outFile.write(compressByteArray, len); outFile.close(); LOG << QString(compressByteArray.mid(0, len).toHex(' ')); // 解壓 QByteArray unCompressByteArray = QByteArray(1024, 0x00); // 入坑一 unCompressLen傳入的時候,做爲指示緩存區的長度,運行完後,做爲傳出實際的長度 int unCompressLen = unCompressByteArray.size(); LOG << unCompressByteArray.size(); ret = uncompress((uchar *)unCompressByteArray.data(), (uLong *)&unCompressLen, (uchar *)compressByteArray.data(), (uLong)len); LOG << ret << unCompressLen << len; if(Z_OK == ret) { LOG << "Succeed to uncompress" << compressByteArray.size() << "to" << unCompressLen; } // 解壓後的存文文件 2.txt QString fileName2 = "2.txt"; QFile file2(fileName2); if(!file2.open(QIODevice::WriteOnly | QIODevice::Truncate)) { LOG; return; } file2.write(unCompressByteArray, unCompressLen); file2.close(); LOG << "restore:" << QString(unCompressByteArray.mid(0, unCompressLen)); }
對應工程模板:zlibDemo_v1.0.0_基礎模板_測試壓縮解壓.rar模塊化
若該文爲原創文章,轉載請註明原文出處
本文章博客地址:https://blog.csdn.net/qq21497936/article/details/111877005測試