Huffman编码对英文文本的压缩和解压缩 中国地质大学计算机学院信息安全专业 信息论实验报告 #include #include #include struct head { unsigned char b; //记录字符在数组中的位置 long count; //字符出现频率(权值) long parent,lch,rch; //定义哈夫曼树指针变量 char bits[256]; //定义存储哈夫曼编码的数组 }header[512],tmp; void compress() { char filename[255],outputfile[255],buf[512]; unsigned char c; long n,m,i,j,f; //作计数或暂时存储数据用 long min1,pt1,flength=0,length1,length2; //记录最小结点、文件长度 double div; //计算压缩比用 FILE *ifp,*ofp; //分别为输入、输出文件指针 printf("\t 请您输入需要压缩的文件(需要路径):"); gets(filename); ifp=fopen(filename,"rb"); if(ifp==NULL){ printf("\n\t 文件打开失败!\n "); system("pause"); return; } printf("\t 请您输入压缩后的文件名(如无路径则默认为桌面文件):"); gets(outputfile); ofp=fopen(outputfile,"wb"); if(ofp==NULL){ printf("\n\t 压缩文件失败!\n "); system("pause"); return; } flength=0; while(!feof(ifp)){ fread(&c,1,1,ifp); header[c].count++; //字符重复出现频率+1 flength++; //字符出现原文件长度+1 } flength--; length1=flength; //原文件长度用作求压缩率的分母 header[c].count--; for(i=0;i<512;i++){ if(header[i].count!=0) header[i].b=(unsigned char)i; /* 将每个哈夫曼码值及其对应的ASCII 码 存放在一维数组 header[i]中,且编码表 中的下标和 ASCII 码满足顺序存放关系*/ else header[i].b=0; header[i].parent=-1;header[i].lch=header[i].rch=-1; // 对结 点进行初始化 } for(i=0;i<256;i++){ //按出现权值从大到小排序 for(j=i+1;j<256;j++){ if(header[i].count