www.pudn.com > Haffman_Compress_and_Decompress.rar > huffcode&decode.h


#include "struct.h" 
# include "string.h" 
#include  
#include 
#include "hufftree.h" 
#include "huff_encode.h" 
 
 
/*************************************** 
*                  蔡敏 
***************************************/ 
 
 
void HaffCompress(HaffCode* hc,int n,char* filename, char_record* w,char* dir) 
{ 
	int i,j; 
	char ch; 
	char*newfilename; 
	newfilename=(char* )malloc(30*sizeof(char)); 
	ofstream ofile; 
	ifstream infile; 
 
	infile.open(filename,ios_base::binary); 
	if(!infile){ 
		cout<<"error: unable to open input file!\n"; 
	} 
 
	for(i=0;filename[i]!=0;i++) 
		; 
	strcpy(newfilename, dir); 
	strcat(newfilename, ".var"); //  may be  "war" 
	ofile.open(newfilename,ios_base::binary|ios_base::app); 
 
	// 写入文件名长度,一字节 
	ofile.put((unsigned char)i); 
	 
	cout<<"HaffCompress...[ "; 
	for(j = 0; j < i; j++){ 
		ofile.put(filename[j]); 
		cout<=0;j--) { 
			s[j] = (unsigned long)(unsigned char)w[i].weight & mask; 
			w[i].weight >>= 8; 
		} 
		for(int j = 0; j <= 3; j++) 
			ofile.put(s[j]); 
	} 
 
	// 将文件内容按照huff编码写入文件 
	char ch2  = 0x00; 
	int count = 0; 
	bool  left = true; 
	ch = infile.get(); 
	while(!infile.eof()) { 
		for(i = 0; i < n; i++) { 
			if((unsigned char)ch == hc[i].ascii_code) { 
				for(j = hc[i].start + 1; j < n; j++) { 
					if(hc[i].bit[j]==1) { 
						ch2 += 1; 
					} 
					else { 
						ch2 += 0; 
					} 
					count++; 
					if(count!=8) { 
						ch2 <<= 1; 
						left = true; 
					} 
					else { 
						ofile.put(ch2); 
						count = 0; 
						ch2   = 0; 
						left = false; 
					} 
				} 
				break; 
			} 
		} 
		infile.get(ch);//继续读下一个字符  
	} 
	if( left ) { 
	//if(count!=8) { 
		for(i = 1; i < 8 - count; i++) { 
			ch2<<=1; 
		} 
		ofile.put(ch2); 
	} 
	ofile.close(); 
	infile.close(); 
} 
 
 
 
void HaffDecompress(char* filename,char* dir)//解压文件  
{ 
	ofstream ofile; 
	ifstream infile; 
	char * newfilename; 
	char ch; 
	newfilename =(char* )malloc(30*sizeof(char)); 
	strcpy(newfilename,dir); 
	strcat(newfilename,"copy"); 
 
	char* temppath; 
	temppath = (char* )malloc(30*sizeof(char)); 
 
	int k; 
	for(k=0;dir[k] != 0;k++) 
		; 
 
	CreateDirectory((LPCSTR)newfilename, NULL);////////////////////////		X 
	infile.open(filename,ios_base::binary); 
	// 读入的是文件名长度 
	infile.get(ch); 
	while(!infile.eof()){ 
 
		cout<<"file name len:"<<(int)ch<>=8; 
			w[j].weight=m; 
		} 
 
		// 重新根据这些权重生成haff树 
		HaffNode* ht = hufftree(w,n); 
		HaffCode* hc = huff_encode(w,n,ht); 
 
		unsigned long long size=0,tempsize=0; 
		for(i=0;i