⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 compress.cpp

📁 可实现压缩功能
💻 CPP
字号:
// LZW compression



#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "chash.h"


const D = 4099,      
      codes = 4096,  
      ByteSize = 8,
      excess = 4,    
      alpha = 256,   
      mask1 = 255,   
      mask2 = 15;    

class element {
   friend void Compress();
   public:
      operator unsigned long() const {return key;}
      element& operator =(unsigned long y)
         {key = y; return *this;}
   private:
      int code;
      unsigned long key;
};


int LeftOver,   
    status = 0; 
ifstream in;
ofstream out;

void SetFiles(int argc, char* argv[])
{
   char OutputFile[50], InputFile[50];
   
   if (argc >= 2) strcpy(InputFile,argv[1]);
   else {
         cout << "Enter name of file to compress"
              << endl;
         cout << "File name should have no extension"  
              << endl;
         cin >> InputFile;}

   
   if (strchr(InputFile,'.')) {
       cerr << "File name has extension" << endl;
       exit(1);}

   
   in.open(InputFile,ios::binary);
   
   if (in.fail()) {cerr << "Cannot open " << InputFile 
                        << InputFile << endl;
                   exit(1);}
   strcpy(OutputFile,InputFile);
   strcat(OutputFile, ".zzz");
   out.open(OutputFile,ios::binary);
   
}

void Output(unsigned long code);

void Compress()
{
   ChainHashTable<element, unsigned long> h(D);
   element e;
   for (int i = 0; i < alpha; i++) {
      e.key = i;
      e.code = i;
      h.Insert(e);
      }
   int used = alpha; 

   
   unsigned char c;
   in.get(c);      
   unsigned long pcode = c; 
   if (!in.eof()) {
      do {
          in.get(c);
          if (in.eof()) break;  
          unsigned long k = (pcode << ByteSize) + c;
          
          if (h.Search(k, e)) pcode = e.code;  
          else {
                Output(pcode);
                if (used < codes) 
                   {e.code = used++;
                    e.key = (pcode << ByteSize) | c;
                    h.Insert(e);}
                pcode = c;}
   	} while(true);

      Output(pcode);
      if (status) {c = LeftOver << excess;
                   out.put(c);}
      }

   out.close();
   in.close();
}

void Output(unsigned long pcode)
{
   unsigned char c,d;
   if (status) {
      d = pcode & mask1; 
      c = (LeftOver << excess) | (pcode >> ByteSize);
      out.put(c);
      out.put(d);
      status = 0;}
   else {
      LeftOver = pcode & mask2;
      c = pcode >> excess;
      out.put(c);
      status = 1;}
}

void main(int argc, char* argv[])
{
   SetFiles(argc, argv);
   Compress();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -