unzip.m
上传用户:xxhxxny
上传日期:2021-02-19
资源大小:87k
文件大小:2k
- %=========================================
- % 文件解压,先从压缩文件头中取出字符频率
- % 构建huffman树,然后完成解压
- %=========================================
- function [] = unzip(fileziped,fileorigin)
- if nargin<1 %程序输入参数
- disp('usage: compress your_zip_filename [your_dest_filename]');
- return;
- end
- if nargin<2
- fileorigin=strcat(fileziped,'.txt');
- end
- fid_in = fopen(fileziped); %打开压缩文件
- if fid_in==-1
- disp('Sorry,input file open failed!');
- return;
- end
- fid_out= fopen(fileorigin,'w'); %建立解压缩的结果文件
- if fid_out==-1
- disp('Sorry,output file open failed!');
- fclose(fid_in);
- return;
- end
- prob=fread(fid_in,256,'uint8'); %从压缩文件中读取前256个字节,该256个字节保存的是256个字符出现的频度
- [huffman_tree,index_tree]=build_tree(prob); %建立霍夫曼树
- bits_stream=fread(fid_in); %读取256个字符后面的实际的压缩文件保存在一个整数数组中
- stream_leng=length(bits_stream); %得到数组长度,待遍历数组使用
- fprintf('nunzipping... stream length is:%d,to check wheather equeal to wirte times when compressingn',stream_leng);
- node=index_tree; %生成的霍夫曼树根节点
- disp('uncompressing file...');
- for stream_index=1:stream_leng %遍历整个数组
- for bit_index=1:8 %对每个整数的8个二进制位进行遍历
- curr_bit=bitand(bits_stream(stream_index),2^(8-bit_index));
- %disp('curr bit:');
- %disp(curr_bit~=0);
- if(curr_bit)
- node=huffman_tree.rightchild(node); %(循环类似于递归)二进制位为0则为右节点
- else
- node=huffman_tree.leftchild(node); %(循环类似于递归)二进制位为0 则为左节点
- end
- %disp('curr node:');
- %disp(node);
- if node<256 %大于256的话则为非叶子节点
- fprintf(fid_out,'%s',char(node));
- node=index_tree;
- elseif node==256 %读到第256则表示读到EOF
- fclose(fid_in);
- fclose(fid_out);
- disp('completed!');
- return;
- end
- end
- end
- disp('completed!');
- fclose(fid_in);
- fclose(fid_out);