/*压缩文件*/
void y_s(FILE *fp,FILE *fp2)
{
int i;
for(i=0;i<256;i++) /*将各字符的权值压入文件头*/
{
fwrite(&hfm[i].weight,sizeof(unsigned int),1,fp2);
}
int cn=0; /*统计当前位数*/
unsigned char b=0;/*存入转成的二进制*/
while(!feof(fp))
{
int nt=0;
unsigned char p;
if(fread(&p,1,1,fp)!= 1) /*每取一个字节*/
break;
while(nt<=code[p].start)
{
if(code[p].bit[nt])
{
b |= 1<<(7-cn); /*将当前字节第几位置零*/
}
nt++;
if((cn+1)==8)
{
fwrite(&b,sizeof(b),1,fp2); /*满8位压入文件*/
b=0; /*清零*/
}
cn = (cn+1)%8; /*满8位清零*/
}
}
if(cn) /*写入尾巴(最后一个没有满8位的)*/
{
fwrite(&b,sizeof(b),1,fp2);
cn=0;
b=0;
}
fclose(fp);
fclose(fp2);
}
int main(int a ,char *str[])
{
FILE *fp=fopen(str[1],"r");/*打开需压缩的文件*/
if(fp == NULL)
{
perror("open file.txt\n");
exit(1);
}
FILE *fp2=fopen(str[2],"w"); /*打开需压缩形成的文件*/
if(fp2 == NULL)
{
perror("open file2.txt\n");
exit(1);
}
unsigned char p;
int i,j;
/*给节点数组赋初值*/
for(i=1;i<511;i++)
{
hfm[i]=hfm[0];
}
/*统计*/
while(!feof(fp))
{
if (fread(&p,1,1,fp) != 1)
break;
hfm[p].weight++;
}
rewind(fp);
hu_fm();
output_count();/*输出统计情况*/
/*查找根节点*/
for(i=510;i>=256;i--)
{
if (hfm[i].weight !=0)
break;
}
unsigned int head=i;
preorder(head);
/*给编码数组赋初值*/
for(i=1;i<256;i++)
{
code[i]=code[0];
}
hf_code();
output_wc();
y_s(fp,fp2);
}