这个程序运行老师出现.exe 文件停止运行
#define M 1000#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct htnode
{
char data;
int weight,parent,lch,rch;
};
struct hcode
{
char cd[M];
int start;
};
struct node
{
char data[M];
int k[M];
}count;
int n=1;
int count1(int n) /* 统计字符个数及每个字符出现的频率*/
{
int i,j,t,N=strlen(count.data);
char ch;
for(i=0;i<N; i++)
{
ch=count.data[i];
for(j=n;j<N;)
if(count.data[j]==ch&&i!=j)
{
count.k[i]++;
for(t=j;t<N;t++)
count.data[t]=count.data[t+1];
N=N-1;
}
else
j++;
if(i==n)
n=n+1;
}
return (N);
}
void transfer(struct node count, struct htnode ht[], int N)
{
int i;
for(i=0;i<N;i++)
{
ht[i].data=count.data[i];
ht[i].weight=count.k[i];
}
ht[i].data='\0';
}
void createht(struct htnode ht[],int n) /*构造哈夫曼树*/
{
int i,k,lnode,rnode,min1,min2;
for(i=0;i<2*n-1;i++)
ht[i].parent=-1,ht[i].lch=-1,ht[i].rch=-1;
for(i=n;i<2*n-1;i++)
{
min1=32767,min2=32767;
lnode=-1,rnode=-1;
for(k=0;k<=i-1;k++)
if(ht[k].parent==-1)
{
if(ht[k].weight<min1)
{
min2=min1;rnode=lnode;
min1=ht[k].weight;lnode=k;
}
else if(ht[k].weight<min2)
min2=ht[k].weight,rnode=k;
}
ht[lnode].parent=i,ht[rnode].parent=i;
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lch=lnode,ht[i].rch=rnode;
}
}
void createhcode(struct htnode ht[],struct hcode hcd[],int n) /* 对叶子结点进行编码 */
{
int i,f,c;
struct hcode hc;
for(i=0;i<n;i++)
{
hc.start=n,c=i;
f=ht[i].parent;
hc.cd[hc.start--]='#';
while(f!=-1)
{
if(ht[f].lch==c)
hc.cd[hc.start--]='0';
else
hc.cd[hc.start--]='1';
c=f,f=ht[f].parent;
}
hc.start++,hcd[i]=hc;
}
}
void encode(struct htnode ht[],struct hcode hcd[],char s2[],char str[])/*对所有字符进行编码*/
{
int k=0,i,j,t;
for(i=0;s2[i]!='\0';i++)
{
j=0;
while(s2[i]!=ht[j].data&&ht[j].data!='\0')
j++;
if(ht[j].data!='\0')
{
t=hcd[j].start;
while(hcd[j].cd[t]!='#')
str[k++]=hcd[j].cd[t++];
}
}
str[k]='\0';
}
int decode(char str[],struct hcode hcd[],struct htnode ht[],char sd[],int n ) /*对所有字符进行译码*/
{
int k=0,j=0,m,t,i=0;
while(str[i]!='\0'&&j<n)
{
t=hcd[j].start;
for(m=i;str[m]==hcd[j].cd[t]&&hcd[j].cd[t]!='#';m++,t++);
if(hcd[j].cd[t]=='#')
sd[k++]=ht[j].data,j=0,i=m;
else
j++;
}
sd[k]='\0';
return i;
}
void main()
{
FILE *fp1,*fp2,*fp3;
struct htnode ht[M];
struct hcode hcd[M];
int i,len, N;
char s2[M],sd[M],str[M];
if((fp1=fopen("D:/yuan.txt","r"))==NULL)
{
printf("你不能打开文件!\n");
exit(0);
}
len=0;
while(!feof(fp1))
{
fgets(&count.data[len],20,fp1);
len=count1(n);
n=len-1;
} //统计叶子节点数
fclose(fp1);
N=len;
transfer(count,ht,N);
createht(ht,N);
createhcode(ht,hcd,N);
fp1=fopen("yuan.txt","r");
if((fp2=fopen("D:/bian.txt","w"))==NULL)
{
printf("can not open file!\n");
exit(0);
}
while(!feof(fp1))
{
fgets(s2,20,fp1);
encode(ht,hcd,s2,str);//编码
fputs(str,fp2);
}
fclose(fp1);
fclose(fp2);
fp2=fopen("D:/bian.txt","r");
if((fp3=fopen("D:/yi.txt","w"))==NULL)
{
printf("can not open file!\n");
exit(0);
}
while(!feof(fp2))
{
fgets(str,20,fp2);
len=strlen(str);
i=decode(str,hcd,ht,sd,N); /*yi ma*/
if(i!=len)
fseek(fp2,-(len-i),1);
fputs(sd,fp3);
}
fclose(fp2);
fclose(fp3);
printf("按任意键退出!!!");
}