1. 程式人生 > >【轉】C++ ZLib壓縮與解壓縮

【轉】C++ ZLib壓縮與解壓縮

  1. #include "stdafx.h"
  2. #include "zlib.h"
  3. #include <iostream>
  4. using namespace std;
  5. #pragma comment(lib,"zlib.lib")
  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8.     int err;
  9.     Byte compr[200], uncompr[200]; //足夠大
  10.     uLong comprLen, uncomprLen;
  11.     const char* hello = "1234567890"; //原文
  12.     uLong len = strlen(
    hello);// + 1;
  13.     comprLen = sizeof(compr) / sizeof(compr[0]);
  14.     err = compress(compr, &comprLen, (const Bytef*)hello, len);
  15.     if (err != Z_OK)
  16.     {
  17.         cerr << "壓縮錯誤: " << err << '\n ';
  18.     }
  19.     cout << "原文長度: " << len << "\n壓縮後長度:" << comprLen <
    < '\n ';
  20.     strcpy((char*)uncompr, "garbage ");
  21.     err = uncompress(uncompr, &uncomprLen, compr, comprLen);
  22.     if (err != Z_OK)
  23.     {
  24.         cerr << "解壓錯誤: " << err << '\n ';
  25.     }
  26.     cout << "\n原文長度:" << len << "\n解壓後長度:" << uncomprLen <
    < '\n ';
  27.     if (strcmp((char*)uncompr, hello))
  28.     {
  29.         cerr << "\n解壓失敗!!!\n ";
  30.     }
  31.     else
  32.     {
  33.         cout << "\n解壓成功:" << (char*)uncompr;
  34.     }
  35.     FILE *f= fopen("d:\\b1.bin","wb");
  36.     fwrite(compr,comprLen,1,f);
  37.     fclose(f);
  38.     getchar();
  39.     return 0;
  40. }
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> 閱讀(3215) | 評論(0) | 轉發(0) | 給主人留下些什麼吧!~~ 評論熱議