哈夫曼压缩解压
#include
#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 i,j,m,n,f;
long min1,pt1,flength,length1,length2;
double div;
FILE *ifp,*ofp;
printf("\t请您输入需要压缩的文件:"); gets(filename);
ifp=fopen(filename,"rb"); if(ifp==NULL)
{
printf("\n\t文件打开失败!\n\n");
return;
}
printf("\t请您输入压缩后的文件名:"); gets(outputfile);
ofp=fopen(strcat(outputfile,".hub"),"wb");
if(ofp==NULL)
{
printf("\n\t压缩文件失败!\n\n");
return;
}
flength=0;
while(!feof(ifp))
{
fread(&c,1,1,ifp);
header[c].count++;
flength++; }
flength--;
length1=flength; header[c].count--;
for(i=0;i<512;i++)
{
if(header[i].count!=0) header[i].b=(unsigned char)i;
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].countheader[j].count)
{
pt1=j;
min1=header[j].count;
continue;
}
}
header[i].count=header[pt1].count;
header[pt1].parent=i;
header[i].lch=pt1;
min1=999999999;
for(j=0;jheader[j].count)
{
pt1=j;
min1=header[j].count;
continue;
}
}
header[i].count+=header[pt1].count;
header[i].rch=pt1;
header[pt1].parent=i; }
for(i=0;i=8)
{
for(i=0;i<8;i++)
{
if(buf[i]=='1') c=(c<<1)|1;
else c=c<<1;
}
fwrite(&c,1,1,ofp);
pt1++;
strcpy(buf,buf+8);
j=strlen(buf);
}
if(f==flength) break; }
if(j>0)
{
strcat(buf,"00000000");
for(i=0;i<8;i++)
{
if(buf[i]=='1') c=(c<<1)|1;
else c=c<<1;
}
fwrite(&c,1,1,ofp);
pt1++;
}
fseek(ofp,4,SEEK_SET); fwrite(&pt1,sizeof(long),1,ofp); fseek(ofp,pt1,SEEK_SET); fwrite(&n,sizeof(long),1,ofp); for(i=0;i0) m=p/8+1;
else m=p/8;
for(j=0;jf;l--)
{
strcat(header[i].bits,"0");
}
strcat(header[i].bits,buf);
}
header[i].bits[p]=0; }
for(i=0;istrlen(header[j].bits))
{
tmp=header[i];
header[i]=header[j];
header[j]=tmp;
}
}
}
p=strlen(header[n-1].bits);
fseek(ifp,8,SEEK_SET); m=0;
bx[0]=0;
while(1)
{
while(strlen(bx)<(unsigned int)p)
{
fread(&c,1,1,ifp);
f=c;
itoa(f,buf,2);
f=strlen(buf);
for(l=8;l>f;l--)
{
strcat(bx,"0");
}
strcat(bx,buf);
}
for(i=0;i