1、HafuTree ht;/*声明一个指向树结点到指针*/typedef struct /*叶子结点字符*/ char codestr20; /*字符编码*/HafuCode;HafuCode code27;/*用于存放对应字符到哈夫曼编码*/void InitHafuArry() /*导入文件计算权值,生成只含有叶子结点的HafuNode数组*/ int j,i,k; HafuNode tmpht; FILE *fp; /*定义一指向打开文件的指针*/*用于存储一个字母*/ char location30=D: ht=(HafuTree)malloc(53*sizeof(HafuNode);
2、/*为哈夫曼数分配内存空间*/ if(ht=NULL) return ; for(i=0;i53;i+) /*初始化所以的数据单元,每个单元自成一棵树*/ hti.w=0; /*权值初始化为0*/ hti.lchild=hti.rchild=-1; /*左右子为空*/ num=0; printf(File name:); scanf(%s,filename); strcat(location,filename); fp=fopen(location,r if(!fp) /*返回1时即存在文件*/Open Error return; while(!feof(fp)/*没到结尾时返回0*/ ch=
3、fgetc(fp); if(ch= |chaZA)%c,ch);) ch=# for(j=0;jnum;j+) if(htj.ch=ch) break; if(j=num) /*找到新字符*/ htnum.ch=ch; /*将新字符存入并将权值加1*/ htnum.w+; num+; else htj.w+; /*将已有字符权值加1*/ fclose(fp);ni+) /*对叶子结点按权值进行升序排序*/ k=i; for(j=i+1; if(htj.wk;j-) /*将新结点插入有序数组中*/ if(htj.whfnode.w) htj+1=htj; else break; htj=hfno
4、de; root=j;/*一直跟随新生成的结点,最后新生成的结点为根结点*/ return root;void GetHafuCode(HafuTree ht,int root,char *codestr) /*ht是哈夫曼树,root是根结点下标,codestr是来暂时存放叶子结点编码的,一开始为空*/ FILE *out; int len,i; if(htroot.lchild=-1) /*遇到递归终点是叶子结点记录叶子结点的哈夫曼编码*/ codecodenum.ch=htroot.ch; strcpy(codecodenum.codestr,codestr); codenum+; el
5、se /*不是终点则继续递归*/ len=strlen(codestr); codestrlen=0 /*左分支编码是0*/ codestrlen+1=0; /*向左孩子递归之前调整编码序列末尾加0,相当于加了个0(null)其十进制值是0,以便下次循环时添加字符,否则会被覆盖掉*/ GetHafuCode(ht,htroot.lchild,codestr); /*向左递归*/ codestrlen-1=1/*右分支编码为1,想右递归之前末尾编码0改为1*/ GetHafuCode(ht,htroot.rchild,codestr); /*向右递归*/ codestrlen-1=0; /*左右
6、孩子递归返回后,删除编码标记末尾*/ out=fopen(code.txt,w+) ;out) /*printf(Write Error */ /*再打开源文件,对照哈夫曼编码译成编码*/ if(ch= /*如果是空格就用#号代替*/codenum; /*找到字符所对应到哈夫曼编码*/ if(ch=codei.ch) /*将所得哈夫曼编码输出到文件中*/ fputs(codei.codestr,out); fclose(fp); /*关闭打开到两个文件*/ fclose(out);void decodeHafuCode(HafuTree ht,int root) /*将哈夫曼编码翻译为明文*/
7、 FILE *fp2; int curr=root;/*当前结点到下标*/ char filename220=/*获得文件名*/ fp2=fopen(location,fp2) /*返回1时即存在文件*/Open Error2Code:feof(fp2)/*没到结尾时返回0*/ ch=fgetc(fp2); if(chch)/*将编码过滤出来*/ /*将密文输出显示*/ rewind(fp2); /*将文件指针位置定位在开头*/) /*如果为0则当前结点向左走*/ if(htcurr.lchild!=-1) curr=htcurr.lchild;/*若有左子则去左子*/ curr=root;
8、/*没有则返回根结点*/) /*如果为1则当前结点向右走*/ if(htcurr.rchild! curr=htcurr.rchild;/*若有右子则去右子*/ if(htcurr.lchild=-1&htcurr.rchild=-1)/*若为叶子结点则打印输出*/,htcurr.ch=?:htcurr.ch); /*回到根结点继续索引*/ fclose(fp2);void main() int root; int i; char codestr20= int control; /*显示菜单可选择编码、译码还是退出*/=Menu=nchose 1:encodenchose 2:decodenc
9、hose 3:exitn%d,&control); while(control!=3) /*只有没有选择退出就一直循环*/ if(control=1) /*选择编码选项*/ FILE *output; InitHafuArry(); /*初始化结点*/ root=CreateHafuman(ht); /*造一棵哈夫曼树*/ GetHafuCode(ht,root,codestr);/*根据哈夫曼树将明文译成密码*/ output=fopen(CODE.TXToutput) /*返回1时即存在文件*/Open Error3 continue;feof(output)/*没到结尾时返回0*/ ch=fgetc(output); fclose(output);/*将打开文件关闭*/ if(control=2) /*如果选择译码,则调用译码函数*/ decodeHafuCode(ht,root); if(control=3) /*如果选择3则退出程序*/ exit(0); /*若没有退出则继续打印菜单提示供选择*/nn=Menu=ngetch();