⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 decompress.cpp

📁 利用Huffman编码法做的一个文本文件压缩程序
💻 CPP
字号:
#include "stdafx.h"
#include "Decompress.h"



/*-------------------------解压缩函数------------------------*/
int fnDecompress(char sAdress[])
{
	CODE *arCode;
	FILE *fpHuf,*fpTxt;
	char sTxtAdress[256],archCodeList[32767]={0};
	unsigned char nCodeLenth,codecell=0;
	int i,j,k,nChCount,nSize;
	int Temp;


	strcpy(sTxtAdress,sAdress);
	sTxtAdress[strlen(sTxtAdress)-3] = 0;
	strcat(sTxtAdress,"txt");
	fpHuf=fopen(sAdress,"rb");
	if(fpHuf == NULL)
	{
	printf("目标文件不存在!!\n");
		return -1;
	}
	printf("正在准备解压......\n");
	fread(&nSize,sizeof(int),1,fpHuf);
	arCode = (CODE *)malloc(nSize*sizeof(CODE));
	if(arCode == NULL)
	{
		printf("内存分配失败!!\n");
		getch();
		return 0;
	}
	for(i=0;i<nSize;i++)
	{
		nChCount=0;	j=0;
		fread(&arCode[i].leaf,1,1,fpHuf);
		fread(&nCodeLenth,1,1,fpHuf);
		arCode[i].code=(char *)malloc((nCodeLenth+1)*sizeof(char));
		if(arCode[i].code == NULL)
			return 0;
		arCode[i].code[nCodeLenth] = 0;
		while(j<=(nCodeLenth-1)/8)
		{
			fread(&codecell,1,1,fpHuf);
			for(k=7;k>=0&&nChCount<nCodeLenth;k--)
			{
				Temp = (int)pow(2,k);
				arCode[i].code[nChCount]=codecell/Temp+48;
				codecell -=Temp*(codecell/Temp);
				nChCount++;
			}
			j++;
		}
		arCode[i].code[nCodeLenth]=0;
	}
	printf("正在进行解压......\n");
	fpTxt = fopen(sTxtAdress,"wt");
	if(fpTxt == NULL)
		return 0;
	while(1)
	{
		if(!myBatfRead(fpHuf,archCodeList))
			break;
		if(!myTxtfWrite(fpTxt,archCodeList,arCode,nSize))
			return 0;
	}
	fclose(fpHuf);
	fclose(fpTxt);
	for(i=0;i<nSize;i++)
		free(arCode[i].code);
	free(arCode);
	return 1;
	
}

/*-------------------读取二进制文件函数-------------------------*/
int myBatfRead(FILE *fpHuf,char archCodeList[])
{
	CODECELL codecell;
	unsigned char nCellNum,nBitNum;
	int i=0,j=0,k;
	int Temp;
	
	if(!fread(&nCellNum,sizeof(char),1,fpHuf))
		return 0;
	fread(&nBitNum,sizeof(char),1,fpHuf);
	if(!nBitNum)
		nBitNum=8;					//nBitNum此处为8是因为压缩时lenth-1,故如此可以保证编码长度不会减少8位
	while(j<=nCellNum)
	{
		fread(&codecell,1,1,fpHuf);
		for(k=7;k>=0;k--)
		{
			Temp = (int)pow(2,k);
			archCodeList[i++]=codecell/Temp+48;
			codecell -=Temp*(codecell/Temp);
		}
		j++;
	}
	archCodeList[nCellNum*8+nBitNum]=0;
	return 1;
}

/*-------------------------写入文本文件函数---------------------------*/
int myTxtfWrite(FILE *fpTxt,char archCodeList[],CODE arCode[],int nSize)
{
	int i=0,j,k,Temp,nSameMark;
	while(archCodeList[i]!=0)
	{
		for(j=0;j<nSize;j++)
		{
			Temp=i;
			nSameMark=1;
			for(k=0;arCode[j].code[k]!=0;k++)
			{
				if(archCodeList[Temp]!=arCode[j].code[k])
				{
					nSameMark = 0;
					break;
				}
				Temp++;
			}
			if(nSameMark)
			{
				fprintf(fpTxt,"%c",arCode[j].leaf);
				i=Temp;
				break;
			}
		}
		if(j==nSize)
			return 0;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -