unzip.m
上传用户:xxhxxny
上传日期:2021-02-19
资源大小:87k
文件大小:2k
源码类别:

压缩解压

开发平台:

Matlab

  1. %=========================================
  2. % 文件解压,先从压缩文件头中取出字符频率
  3. % 构建huffman树,然后完成解压
  4. %=========================================
  5. function [] = unzip(fileziped,fileorigin)
  6. if nargin<1   %程序输入参数
  7.     disp('usage: compress your_zip_filename [your_dest_filename]');
  8.     return;
  9. end
  10. if nargin<2
  11.     fileorigin=strcat(fileziped,'.txt');
  12. end
  13. fid_in = fopen(fileziped);   %打开压缩文件
  14. if fid_in==-1
  15.     disp('Sorry,input file open failed!');
  16.     return;
  17. end
  18. fid_out= fopen(fileorigin,'w');   %建立解压缩的结果文件
  19. if fid_out==-1
  20.     disp('Sorry,output file open failed!');
  21.     fclose(fid_in);
  22.     return;
  23. end
  24. prob=fread(fid_in,256,'uint8');   %从压缩文件中读取前256个字节,该256个字节保存的是256个字符出现的频度
  25. [huffman_tree,index_tree]=build_tree(prob);   %建立霍夫曼树
  26. bits_stream=fread(fid_in);   %读取256个字符后面的实际的压缩文件保存在一个整数数组中
  27. stream_leng=length(bits_stream);   %得到数组长度,待遍历数组使用
  28. fprintf('nunzipping... stream length is:%d,to check wheather equeal to wirte times when compressingn',stream_leng);
  29. node=index_tree;   %生成的霍夫曼树根节点
  30. disp('uncompressing file...');
  31. for stream_index=1:stream_leng   %遍历整个数组
  32.     for bit_index=1:8   %对每个整数的8个二进制位进行遍历
  33.         curr_bit=bitand(bits_stream(stream_index),2^(8-bit_index));
  34.         %disp('curr bit:');
  35.         %disp(curr_bit~=0);
  36.         if(curr_bit)
  37.             node=huffman_tree.rightchild(node);   %(循环类似于递归)二进制位为0则为右节点
  38.         else
  39.             node=huffman_tree.leftchild(node);   %(循环类似于递归)二进制位为0 则为左节点
  40.         end
  41.         %disp('curr node:');
  42.         %disp(node);
  43.         if node<256   %大于256的话则为非叶子节点
  44.             fprintf(fid_out,'%s',char(node));
  45.             node=index_tree;
  46.         elseif node==256   %读到第256则表示读到EOF
  47.             fclose(fid_in);
  48.             fclose(fid_out);
  49.             disp('completed!');
  50.             return;
  51.         end
  52.     end
  53. end
  54. disp('completed!');
  55. fclose(fid_in);
  56. fclose(fid_out);