huffman 文件压缩

来源:互联网 发布:恒大淘宝目前市值 编辑:程序博客网 时间:2024/05/24 04:48
利用huffman编码的思想对文件进行压缩,主要原理是通过huffman编码来重新表示字符,使得出现频率高的字符编码短,出现少的字符编码长。整体下来的话,所需的总的bit位是减少的。但是要注意当大部分字符出现的频率都差不多时,huffman压缩的压缩效率会很低。

一、利用huffman树对文件进行压缩主要分为以下两部分:

压缩:
1、统计字符出现的次数
   因为文件的底层都是有256个字符存储的,所以我们使用一个256的数组来统计字符出现的次数。可以使用结构体,将次数,字符,huffman编码对应起来。要注意,不管是文件、图片、音频、视频他们的底层都是以字符形式存储的。我们读的时候不管是以文本形式还是以二进制形式都是按字符读取的。

2、构建huffman树
   采用huffman算法,将一组集合中权值最小的两个树拿出来构建成一棵树,将他们的权值之和作为父节点插入到这个集合中,不断重复这个过程,直到集合中只有一颗树,这棵树就是huffman树,由于每次都要寻找最小的两个数,我们可以使用最小堆来寻找最小的两个数。在这里,我们可以用字符出现的次数作为权值。

3、得到huffman编码
   从根节点出发,向左走位0,向右走为1,找到一个叶子结点,就将他对应字符的huffman编码存到数组里面。

4、将huffman编码写入文件
   使用哈希表,可以在O(1)时间内找到字符所对应的编码,将每8位编码构成一个字符写入文件中。如果最后的几位编码不够8位,那么我们就要在后面几位中补0.

5、编写配置文件
   由于在解压时往往是没有源文件的,而我们要解压的话必须要知道这棵huffman树,所以在我们压缩的时候编写一个配置文件来存储huffman树的信息。在配置文件里面将:字符+出现的次数存在一行。在这里要使用itoa这个函数将次数转换成一个字符串存储。


解压缩:

1、读取配置文件
   由于解压和压缩往往不是一起的,所以在解压之前我们要先还原huffman这棵树,读取配置文件时我们是一行一行进行存储的,所以读的时候我么最好一行一行的读。但是这里要注意两个问题。第一:因为string底层是char*,而每一行的第一个字符是0—255,所以这一块我们要进行处理,可以单独读取。第二:将字符串转换为数字,使用atoi函数。

2、构建huffman树
   构建huffman树和压缩时是一样的。

3、解压缩
   首先在压缩文件里面读取一个字符,然后解析这个字符的每一位,采用贪心法,只要遇到一个叶子结点,就代表我们还原了一个字符,这时候我们就要将这个字符写到解压缩文件里面。但是在这里要注意,有可能最后的几位编码是我们补上去的,所以在这里我们要以源文件中字符出现的次数来控制解压缩,根据huffman的性质可知,根节点的权重就是字符出现的次数。


二、在项目中遇到的问题
    1、解压缩时解压不完全
    由于使用文本形式读取压缩文件,有可能提前遇到文件结束标志,所以要改为二进制形式读写。二进制形式是读取二进制编码。
    如果以文本形式读取的话,回车会被当成一个字符'\n',而二进制形式则会认为它是两个字符即'\r'回车、'\n'换行;如果在文本形式中遇到0x1B的话,文本形式会认为这是文本结束符,而二进制模型则不会对它产生处理。

    2、得到huffman编码
    在压缩时我们要求解huffman编码,在这里可以使用stl中的string和reverse求解。也可以使用后序递归直接求解。

    3、二次压缩效率很低
    因为压缩一次之后,这时因为配置文件中字符出现的次数相差都不是很大,体现不出来huffman的特性。所以这时候再压缩的话效率会非常低下。

    4、压缩汉字时出现问题
    因为汉字是由多个字符表示,这些字符的范围是0—255,所以在结构体中要用unsigned char表示。

三、项目改进
    1、解压缩的时候有可能要解压缩文件的不是用huffman进行压缩的文件。所以再解压文件之前先判断是不是用huffman进行压缩的。
    2、不使用配置文件时如何解压
    可以将huffman树的信息写入到压缩文件中。

四、项目扩展
    1、实现对文件夹的压缩
    对文件夹进行压缩实际上还是对文件夹中的内容进行压缩,所以得到一个文件夹之后我们就一直向子文件夹中找,直到找到文件后进行压缩就可以了。
    2、解压缩的时候要将文件夹还原出来。

//heap
[cpp] view plain copy
  1. #pragma once  
  2. #include<cassert>  
  3. #include<vector>  
  4. using namespace std;  
  5.   
  6. template<typename T>  
  7. struct Less  
  8. {  
  9.     bool operator()(const T& l, const T& r)  
  10.     {  
  11.         return l < r;  
  12.     }  
  13. };  
  14.   
  15. template<typename T>  
  16. struct Great  
  17. {  
  18.     bool operator()(const T& l, const T& r)  
  19.     {  
  20.         return l>r;  
  21.     }  
  22. };  
  23.   
  24.   
  25.   
  26. //通过仿函数,可以建最小堆也可以建最大堆  
  27. template<typename T, class Compare = Less<T>>  
  28. class Heap  
  29. {  
  30. public:  
  31.     Heap()  
  32.     {}  
  33.     Heap(T *a, int size)  
  34.     {  
  35.         _a.reserve(size);  
  36.         for (int i = 0; i < size; i++)  
  37.         {  
  38.             _a.push_back(a[i]);  
  39.         }  
  40.   
  41.         //建堆  
  42.         for (int i = (size - 2) / 2; i >= 0; --i)     //从最后一个非叶结点开始调整  
  43.         {  
  44.             AdjustDown(i, size);  
  45.         }  
  46.     }  
  47.   
  48.     void Push(const T& x)  
  49.     {  
  50.         //插入到尾部,再从最后一个元素开始向上调整  
  51.         _a.push_back(x);  
  52.         AdjustUp(_a.size() - 1);  
  53.     }  
  54.   
  55.     void Pop()  
  56.     {  
  57.         //将堆顶与最后一个元素交换,再从堆顶下滑调整  
  58.         assert(!_a.empty());  
  59.         swap(_a[0], _a[_a.size() - 1]);  
  60.         _a.pop_back();  
  61.         if (_a.size()>1)         //如果堆中的元素大于一个,再进行调整  
  62.         {  
  63.             AdjustDown(0, _a.size());  
  64.         }  
  65.     }  
  66.   
  67.     size_t Size()  
  68.     {  
  69.         return _a.size();  
  70.     }  
  71.   
  72.     bool Empty()  
  73.     {  
  74.         return _a.empty();  
  75.     }  
  76.   
  77.     const T& Top()  
  78.     {  
  79.         assert(!_a.empty());  
  80.         return _a[0];  
  81.     }  
  82. protected:  
  83.     void AdjustDown(int root, int size)      //向下调整算法  
  84.     {  
  85.         assert(!_a.empty());  
  86.         int parent = root;  
  87.         int child = parent * 2 + 1;  
  88.         while (child<size)  
  89.         {  
  90.   
  91.             if ((child + 1) < size  
  92.                 &&Compare()(_a[child + 1], _a[child]))  //找左右孩子中最大的下标  
  93.                 child++;  
  94.             if (Compare()(_a[child], _a[parent]))  
  95.             {  
  96.                 swap(_a[parent], _a[child]);  
  97.                 parent = child;  
  98.                 child = parent * 2 + 1;  
  99.             }  
  100.             else  
  101.             {  
  102.                 break;  
  103.             }  
  104.         }  
  105.     }  
  106.   
  107.     void AdjustUp(int child)    //向上调整算法  
  108.     {  
  109.         assert(!_a.empty());  
  110.         while (child>0)  
  111.         {  
  112.             int parent = (child - 1) / 2;  
  113.             if (Compare()(_a[child], _a[parent]))  
  114.             {  
  115.                 swap(_a[parent], _a[child]);  
  116.                 child = parent;  
  117.             }  
  118.             else  
  119.             {  
  120.                 break;  
  121.             }  
  122.         }  
  123.     }  
  124. private:  
  125.     vector<T> _a;  
  126. };  



//huffman
[cpp] view plain copy
  1. #pragma once  
  2. #include"heap.h"  
  3.   
  4. template<typename T>  
  5. struct HuffmanNode  
  6. {  
  7.     T _data;  
  8.     HuffmanNode<T>* _left;  
  9.     HuffmanNode<T>* _right;  
  10.     HuffmanNode<T>* _parent;  
  11.     HuffmanNode(const T& data = T())  
  12.         :_data(data)  
  13.         , _left(NULL)  
  14.         , _right(NULL)  
  15.         , _parent(NULL)  
  16.     {}  
  17. };  
  18.   
  19.   
  20. template<typename T>  
  21. class HuffmanTree  
  22. {  
  23.     typedef HuffmanNode<T> Node;  
  24. public:  
  25.     HuffmanTree()  
  26.         :_root(NULL)  
  27.     {}  
  28.   
  29.     HuffmanTree(T  *a, size_t size,const T& invalid=T())  
  30.     {  
  31.         //最小堆的比较方式  
  32.         struct NodeLess  
  33.         {  
  34.             bool operator()(Node* l, Node* r)  
  35.             {  
  36.                 assert(l);  
  37.                 assert(r);  
  38.                 return l->_data < r->_data;  
  39.             }  
  40.         };  
  41.   
  42.         //将这组数据建成一个最小堆,堆中元素的类型是Node*,这是为了保存后面结点的父节点  
  43.         Heap<Node*, NodeLess>  minHeap;  
  44.         for (size_t i = 0; i <size; i++)  
  45.         {  
  46.             if (a[i]._count!=invalid._count)           //如果字符出现的次数不为0,就加入堆中  
  47.             {  
  48.                 Node* _node = new Node(a[i]);  
  49.                 minHeap.Push(_node);  
  50.             }  
  51.         }  
  52.   
  53.         //用huffman算法,从堆里面取出最小的两个结点并删除,将这两个结点构成一棵树在插入堆中  
  54.         Node* frist = NULL;  
  55.         Node* second = NULL;  
  56.         Node* parent = NULL;  
  57.         while (minHeap.Size()>1)  
  58.         {  
  59.             frist = minHeap.Top();  
  60.             minHeap.Pop();  
  61.             second = minHeap.Top();  
  62.             minHeap.Pop();  
  63.   
  64.             parent = new Node(frist->_data + second->_data);  
  65.             parent->_left = frist;  
  66.             parent->_right = second;  
  67.   
  68.             frist->_parent = parent;  
  69.             second->_parent = parent;  
  70.   
  71.             minHeap.Push(parent);  
  72.         }  
  73.   
  74.         //堆里面的最后一个就是Huffman树的根节点  
  75.         _root = minHeap.Top();  
  76.     }  
  77.   
  78.     Node* GetRoot()  
  79.     {  
  80.         return _root;  
  81.     }  
  82.   
  83.   
  84.     ~HuffmanTree()  
  85.     {  
  86.         if (_root != NULL)  
  87.         {  
  88.             Destory(_root);  
  89.         }  
  90.     }  
  91. protected:  
  92.     void Destory(Node * root)  
  93.     {  
  94.         if (root == NULL)  
  95.             return;  
  96.         Node* cur = root;  
  97.         Destory(cur->_left);  
  98.         Destory(cur->_right);  
  99.         delete cur;  
  100.         cur = NULL;  
  101.     }  
  102.   
  103. private:  
  104.     Node* _root;  
  105. };  


//file compress
[cpp] view plain copy
  1. #pragma once  
  2. #include<string>  
  3. #include<cstdio>  
  4. #include<cassert>  
  5. #include <direct.h>  
  6. #include <stdlib.h>  
  7. #include<cstdlib>  
  8. #include<algorithm>  
  9. #include<vector>  
  10. #include<io.h>  
  11. #include<cstring>  
  12. using namespace std;  
  13. #include"HuffmanTree.h"  
  14.   
  15.   
  16.   
  17. typedef long long LongType;  
  18.   
  19. struct CharInfo  
  20. {  
  21.     unsigned char _data;  
  22.     LongType _count;                //保存字符出现的次数  
  23.     string _Code;                   //保存Huffman编码  
  24.     CharInfo(LongType count=0)  
  25.         :_count(count)  
  26.     {}  
  27.   
  28.     CharInfo operator+(CharInfo& ch)  
  29.     {  
  30.         return CharInfo(_count+ch._count);  
  31.     }  
  32.   
  33.     bool operator<(CharInfo &ch)  
  34.     {  
  35.         return _count < ch._count;  
  36.     }  
  37. };  
  38.   
  39.   
  40. class HuffFileCompress  
  41. {  
  42. public:  
  43.     HuffFileCompress()  
  44.     {  
  45.         for (int i = 0; i < 256; i++)   //将Infos中每个data初始化相应的字符  
  46.         {  
  47.             _Infos[i]._data = i;  
  48.         }  
  49.     }  
  50.   
  51.     const string CompressFile(string filename)  
  52.     {  
  53.         vector<string> file;  
  54.         string path = filename.c_str();  
  55.         getFiles(path, file);  
  56.   
  57.         if (file.empty())     //如果为空,则表示是一个文件  
  58.         {  
  59.              return _CompressFile(filename);  
  60.         }  
  61.         else                        //一个文件夹  
  62.         {   
  63.             //首先创建一个新的文件夹  
  64.             string newpath=path;               //新的压缩后文件夹的路径名  
  65.             newpath += ".huf";  
  66.             _mkdir(newpath.c_str());   //  
  67.   
  68.             for (int i = 0; i < (int)file.size(); i++)  
  69.             {  
  70.                 _CompressFile(file[i],newpath);  
  71.             }  
  72.             return newpath;          //返回新建的压缩文件夹的名字  
  73.         }  
  74.     }  
  75.   
  76.     const string UnCompressFile(string filename)  
  77.     {  
  78.         vector<string> file;  
  79.         string path = filename.c_str();  
  80.         getFiles(path, file);  
  81.   
  82.         if (file.empty())     //如果为空,则表示是一个文件进行解压缩  
  83.         {  
  84.             return _UnCompressFile(filename);  
  85.         }  
  86.         else                        //一个文件夹进行解压缩  
  87.         {  
  88.             //首先创建一个新的文件夹  
  89.             string newpath =filename;               //新文件夹  
  90.             for (int i = (int)filename.size() - 1; i >= 0; i--)  
  91.             {  
  92.                 if (filename[i] == '.')  
  93.                 {  
  94.                     newpath.resize(i);  
  95.                     break;  
  96.                 }  
  97.             }  
  98.             newpath += ".uhuf";                  //新文件夹的路径名  
  99.             _mkdir(newpath.c_str());             //创建一个新的解压缩的文件夹  
  100.   
  101.             for (int i = 0; i < (int)file.size(); i++)  
  102.             {  
  103.                 _UnCompressFile(file[i], newpath);  
  104.             }  
  105.             return newpath;          //返回新建的文件夹  
  106.         }  
  107.     }  
  108. protected:  
  109.     //文件压缩  
  110.     const string _CompressFile(const string filename,const string path=string())  
  111.     {  
  112.         CreatHuffmanTree(filename.c_str());  
  113.         //得到压缩文件的文件名  
  114.         string CompressFileName = filename;  
  115.         CompressFileName += ".huf";  
  116.   
  117.         FILE *fInput = fopen(filename.c_str(),"rb");     //打开原文件  
  118.         assert(fInput);  
  119.         FILE *fOut=NULL;  
  120.   
  121.         string configFileName = filename;          //配置文件名  
  122.         configFileName += ".config";  
  123.         FILE *configOut=NULL;  
  124.   
  125.         if (path.empty())            //为空表示是单个文件  
  126.         {  
  127.             fOut = fopen(CompressFileName.c_str(), "wb");   //打开压缩文件  
  128.             if (fOut == NULL)  
  129.             {  
  130.                 fclose(fOut);  
  131.                 exit(EXIT_FAILURE);  
  132.             }  
  133.             //编写配置文件,保存字符以及字符出现的次数,用于解压时重建huffmanTree  
  134.             configOut = fopen(configFileName.c_str(), "wb");   //打开配置文件  
  135.             assert(configOut);  
  136.         }  
  137.         else             //不为空表示是文件夹  
  138.         {  
  139.             //得到要创建的路径  
  140.             string FileName;          //得到文件名  
  141.             int i = filename.size()- 1;  
  142.             for (; i >=0;i--)  
  143.             {  
  144.                 if (filename[i] == '\\')  
  145.                     break;  
  146.                 FileName += filename[i];  
  147.             }  
  148.             reverse(FileName.begin(), FileName.end());  
  149.   
  150.             string newpath=path;  
  151.             newpath += '\\';  
  152.             newpath += FileName;  
  153.             newpath += ".huf";  
  154.             fOut = fopen(newpath.c_str(), "wb");   //打开压缩文件  
  155.             if (fOut == NULL)  
  156.             {  
  157.                 fclose(fOut);  
  158.                 exit(EXIT_FAILURE);  
  159.             }  
  160.   
  161.             //编写配置文件,保存字符以及字符出现的次数,用于解压时重建huffmanTree  
  162.             newpath = path;  
  163.             newpath += '\\';  
  164.             newpath += FileName;  
  165.             newpath += ".config";  
  166.             configOut = fopen(newpath.c_str(), "wb");   //打开配置文件  
  167.             assert(configOut);  
  168.         }  
  169.   
  170.         string line;  
  171.         for (int i = 0; i < 256; i++)  
  172.         {  
  173.             if (_Infos[i]._count!=0)         //将字符以及出现的次数存在一行  
  174.             {  
  175.                 int c=_Infos[i]._data;  
  176.                 fputc(c,configOut);  
  177.                 line += ",";  
  178.                 char buffer[25] = { 0 };      //将次数转换成字符串存储  
  179.                 line+=_itoa((int)_Infos[i]._count, buffer, 10);  
  180.                 line += '\n';  
  181.                 fwrite(line.c_str(),1,line.size(),configOut);  
  182.                 line.clear();  
  183.             }  
  184.         }  
  185.         fclose(configOut);                  //关闭配置文件  
  186.   
  187.         int c=0;                //用来保存huffman编码所构成的字符  
  188.         int pos =7;             //判断处理的位数,如果到8则进行写入  
  189.         int ch = fgetc(fInput);  
  190.         while (ch!=EOF)  
  191.         {  
  192.             string &code=_Infos[ch]._Code;  
  193.             for (size_t i = 0; i < code.size(); i++)     //处理ch这个字符的编码  
  194.             {  
  195.                 c |= ((code[i]-'0') << pos);             //从高位开始相或  
  196.                 pos--;  
  197.                 if (pos<0)  
  198.                 {  
  199.                     fputc(c,fOut);  
  200.                     pos = 7;  
  201.                     c = 0;  
  202.                 }  
  203.             }  
  204.             ch = fgetc(fInput);  
  205.         }  
  206.   
  207.         if (pos<7)   //处理最后一个字符编码不是8位的情况  
  208.         {  
  209.             fputc(c, fOut);  
  210.         }   
  211.         fclose(fOut);  
  212.         fclose(fInput);  
  213.         memset(_Infos, 0, 256 * sizeof(CharInfo));  
  214.         return CompressFileName;  
  215.     }  
  216.   
  217.   
  218.     //解压缩  
  219.     const string _UnCompressFile(string filename,const string path=string())  
  220.     {  
  221.         assert(!filename.empty());  
  222.   
  223.         //得到解压缩之后的文件的名字  
  224.         string name;  
  225.         name= filename;  
  226.         int i = 0;  
  227.         string posfix;  
  228.         for (i =(int)filename.size()-1; i>=0; --i)       //找到后缀出现的位置  
  229.         {  
  230.             posfix.push_back(filename[i]);  
  231.             if (filename[i] == '.')  
  232.                 break;  
  233.         }  
  234.         reverse(posfix.begin(),posfix.end());       //让posfix保存要解压文件的后缀  
  235.   
  236.         if (posfix!= ".huf")                 //如果要解压的文件不是huffman压缩的,则不能解压  
  237.         {  
  238.             return string();  
  239.         }  
  240.         //去掉后缀  
  241.         name.resize(i);  
  242.   
  243.         string UnCompressFileName = name;      //得到压缩文件名   
  244.         UnCompressFileName += ".uhuf";  
  245.   
  246.         string configName = name;  
  247.         configName+=".config";   //得到配置文件名  
  248.   
  249.         //打开压缩文件  
  250.         FILE *fInput = fopen(filename.c_str(),"rb");  
  251.         assert(fInput);  
  252.   
  253.         FILE *configInput=fopen(configName.c_str(), "rb");       //打开配置文件  
  254.         assert(configInput);  
  255.   
  256.         FILE *fOut = NULL;              //解压缩文件  
  257.         if (path.empty())             //如果为空,表示是单个文件解压  
  258.         {  
  259.             //打开解压缩文件  
  260.             fOut = fopen(UnCompressFileName.c_str(), "wb");  
  261.             if (fOut == NULL)  
  262.             {  
  263.                 fclose(fInput);  
  264.                 exit(EXIT_FAILURE);  
  265.             }  
  266.         }  
  267.         else                           //文件夹进行解压缩  
  268.         {  
  269.             string FileName;         //先得到压缩的文件名  
  270.             for (int i = (int)name.size() - 1; i >= 0; i--)  
  271.             {  
  272.                 if (name[i] == '\\')  
  273.                 {  
  274.                     break;  
  275.                 }  
  276.                 FileName += name[i];  
  277.             }  
  278.             reverse(FileName.begin(), FileName.end());  
  279.   
  280.             string newpath = path;  
  281.             newpath += "\\";  
  282.             newpath += FileName;  
  283.             newpath += ".uhuf";  
  284.   
  285.             //打开解压缩文件  
  286.             fOut = fopen(newpath.c_str(), "wb");  
  287.             if (fOut == NULL)  
  288.             {  
  289.                 fclose(fInput);  
  290.                 exit(EXIT_FAILURE);  
  291.             }  
  292.         }  
  293.   
  294.         string line;  
  295.         int c = 0;  
  296.         while ((c = fgetc(configInput))!=EOF)          //读取一行  
  297.         {  
  298.             GetLine(configInput, line);                    
  299.             _Infos[c]._count = atoi((&line[1]));       //获得字符出现的次数  
  300.             line.clear();  
  301.         }  
  302.         fclose(configInput);    //关闭配置文件  
  303.   
  304.         int ch = 0;  
  305.         //构建huffman树  
  306.         CharInfo invalid;  
  307.         for (int i = 0; i < 256; i++)   //将Infos中每个data初始化相应的字符  
  308.         {  
  309.             _Infos[i]._data = i;  
  310.         }  
  311.         HuffmanTree<CharInfo> ht(_Infos, 256, invalid);  
  312.         LongType count = ht.GetRoot()->_data._count;      //获取字符的总个数  
  313.   
  314.         int pos=7;  
  315.         c = 1;  
  316.         HuffmanNode<CharInfo> *root= ht.GetRoot();           //得到huffman树的根节点  
  317.         HuffmanNode<CharInfo> *cur = root;        
  318.         while (count > 0)                         //以字符的总个数作为结束标志  
  319.         {  
  320.             ch = fgetc(fInput);  
  321.             //处理ch的二进制  
  322.             while (pos >= 0 && count > 0)  
  323.             {  
  324.                 //寻找叶子结点(编码所对应的字符)  
  325.                 if (ch&(c << pos))  
  326.                 {  
  327.                     cur = cur->_right;  
  328.                 }  
  329.                 else  
  330.                 {  
  331.                     cur = cur->_left;  
  332.                 }  
  333.                 if (cur->_left == NULL&&cur->_right == NULL)    //找到huffman所对应的字符  
  334.                 {  
  335.                     //写文件  
  336.                     //if (cur->_data._data == '\n')  
  337.                     //  fputc(13, fOut);  
  338.                     fputc(cur->_data._data, fOut);  
  339.                     cur = root;  
  340.                     count--;  
  341.                 }  
  342.                 pos--;  
  343.             }  
  344.             pos = 7;  
  345.         }  
  346.         fclose(fInput);  
  347.         fclose(fOut);  
  348.         memset(_Infos, 0, 256 * sizeof(CharInfo));  
  349.         return UnCompressFileName;  
  350.     }  
  351.   
  352. protected:  
  353.     void CreatHuffmanTree(const char * filename)  
  354.     {  
  355.         assert(filename != NULL);  
  356.         for (int i = 0; i < 256; i++)   //将Infos中每个data初始化相应的字符  
  357.         {  
  358.             _Infos[i]._data = i;  
  359.         }  
  360.   
  361.         FILE *fInput = fopen(filename, "rb");   //打开文件  
  362.         assert(fInput);  
  363.         int ch = 0;  
  364.   
  365.         while ((ch = fgetc(fInput)) != EOF)    //读文件,统计字符出现次数  
  366.         {  
  367.             _Infos[ch]._count++;  
  368.         }  
  369.   
  370.         //构建huffman树  
  371.         CharInfo invalid;  
  372.         HuffmanTree<CharInfo> ht(_Infos, 256, invalid);  
  373.   
  374.         //得到huffman编码  
  375.         string str;  
  376.         GetHufCode(ht.GetRoot(), str);  
  377.         fclose(fInput);  
  378.     }  
  379.   
  380.   
  381.     //得到huffman编码  
  382.     void GetHufCode(HuffmanNode<CharInfo>* root, string str)  
  383.     {  
  384.         if (root == NULL)  
  385.             return;  
  386.         if (root->_left == NULL&&root->_right == NULL)  
  387.         {  
  388.             _Infos[root->_data._data]._Code = str;  //将huffman编码保存在infos里面  
  389.             return;  
  390.         }  
  391.         GetHufCode(root->_left, str + '0');    //向左子树走压0   
  392.         GetHufCode(root->_right, str + '1');   //向右子树走压1       
  393.     }  
  394.   
  395.     bool GetLine(FILE*& Input,string &line)        //读取一行字符  
  396.     {  
  397.         assert(Input);  
  398.         int ch = 0;  
  399.         ch = fgetc(Input);  
  400.         if (ch == EOF)  
  401.             return false;  
  402.         while (ch != EOF&&ch != '\n')  
  403.         {  
  404.             line += ch;  
  405.             ch = fgetc(Input);  
  406.         }  
  407.         return true;  
  408.     }  
  409.   
  410.     void getFiles(string path, vector<string>& files)  
  411.     {  
  412.         //文件句柄  
  413.         long   hFile = 0;  
  414.         //文件信息  
  415.         struct _finddata_t fileinfo;  
  416.         string p;  
  417.         if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)  
  418.         {  
  419.             do  
  420.             {  
  421.                 //如果是目录,迭代之  
  422.                 //如果不是,加入列表  
  423.                 if ((fileinfo.attrib &  _A_SUBDIR))  
  424.                 {  
  425.                     if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)  
  426.                         getFiles(p.assign(path).append("\\").append(fileinfo.name), files);  
  427.                 }  
  428.                 else  
  429.                 {  
  430.                     files.push_back(p.assign(path).append("\\").append(fileinfo.name));  
  431.                 }  
  432.             } while (_findnext(hFile, &fileinfo) == 0);  
  433.             _findclose(hFile);  
  434.         }  
  435.     }  
  436. private:  
  437.     CharInfo _Infos[256];  
  438. };  
原创粉丝点击