中文压缩和解码程序设计与实现(huffman)

2024-06-19 10:18

本文主要是介绍中文压缩和解码程序设计与实现(huffman),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本项目是利用huffman算法进行中文压缩和解码的设计与实现,huffman算法被证明是最优的结构,可以用于数据压缩

源码

/**************************************************************************************
**	this function is about to  compress a file with  chinese code
**	by using huffman method
**	NEWPLAN @ UESTC 2014.5
****************************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>#define SUCCESS		1
#define FAILURE 	0
#define DICTIONRAY	0
#define INDEX 		1/*used to calculate the frequence of character has shown*******/
int array_char[256]= {0};
unsigned char amounts=0;
/*******define a strcuture to hold the tree node***************/
#pragma pack(1)
typedef struct huff
{struct huff *lchild,*rchild,*parent;int wight;unsigned char code;
} HUFF_NODE,*HUFF_NODE_PTR;
#pragma pack()/*HEAD of tree*/
HUFF_NODE_PTR HUFF_HEADER=NULL;
/*dictionary of characters maybe not been used all just for convenient*/
char* HUFF_DICTIONARY[256]= {0};
HUFF_NODE_PTR huff_pt[256];void help(void);
void version(void);
void output(char*);
void initilize(void);
int claculate(FILE*);
int create_dictiony(void);
void compress(const char*);
int file_write(char*,FILE*);
void write_dictionary(char*);
FILE* file_open(const char*);
int create_tree(HUFF_NODE_PTR* );
void decompress_func(const char*);
void decode (HUFF_NODE_PTR,FILE*);
HUFF_NODE_PTR tree_from_dic(char**);
HUFF_NODE_PTR huff_malloc(unsigned char i);
void swap_func(unsigned char *,unsigned char*);
HUFF_NODE_PTR adjusty(HUFF_NODE_PTR code[] ,size_t);//********************************************************
// Method:    main
// FullName:  main
// Access:    public
// Returns:   int
// Qualifier: the entry function
// Parameter: int argc the parameter count
// Parameter: char const * argv[] array of hold parameter
//********************************************************
int main(int argc, char const *argv[])
{initilize();if(argc<2){printf("can`t be empty file or operation\n");return FAILURE;}// if((file_index=file_open(argv[argc-1]))==NULL)if (!stricmp(argv[1],"--help")){help();return SUCCESS;}else if (!stricmp(argv[1],"--version")){version();return SUCCESS;}else if (!stricmp(argv[1],"-c")){compress(argv[2]);}else if(!stricmp(argv[1],"-z")){decompress_func(argv[2]);}elsehelp();return SUCCESS;
}//************************************
// Method:    initilize
// FullName:  initilize
// Access:    public
// Returns:   void
// Qualifier: inites
// Parameter: void
//************************************
void initilize(void)
{int calcount=0;//memset(array_char,'0',sizeof(array_char));while(calcount<256){array_char[calcount]=0;huff_pt[calcount]=NULL;HUFF_DICTIONARY[calcount]=0;calcount++;}return ;
}//************************************
// Method:    file_open
// FullName:  file_open
// Access:    public
// Returns:   FILE*
// Qualifier: open the input file
// Parameter: const char * file_name
//************************************
FILE* file_open(const char* file_name)
{FILE* file_index=NULL;if((file_index=fopen(file_name,"r"))==NULL)return NULL;return file_index;
}//******************************************************************
// Method:    claculate
// FullName:  claculate
// Access:    public
// Returns:   int
// Qualifier: calculate the frequence of character in file_index
// Parameter: FILE * file_index
//****************************************************************
int claculate(FILE* file_index)
{unsigned char temp=0;while(!feof(file_index)){/*eat file*/if(fread(&temp,sizeof(unsigned char),1,file_index))array_char[temp]++;}return SUCCESS;
}//************************************
// Method:    create_dictiony
// FullName:  create_dictiony
// Access:    public
// Returns:   int
// Qualifier:create dictionary
// Parameter: void
//************************************
int create_dictiony(void)
{int i=0;char *u=NULL;unsigned char j=0;HUFF_NODE_PTR head,currents=NULL;create_tree(&head);HUFF_HEADER=head;while(i<256){if(huff_pt[i]!=NULL){currents=huff_pt[i];j=currents->code;u=malloc(sizeof(char));assert(u!=NULL);memset(u,0,sizeof(char));while(currents->parent!=NULL){u=realloc(u,2*sizeof(char)+strlen(u));assert(u!=NULL);if(currents->parent->lchild==currents)strcat(u,"0");else if(currents->parent->rchild==currents)strcat(u,"1");else{printf("error in code\n");system("pasue");}currents=currents->parent;}/*reverse*/strrev(u);HUFF_DICTIONARY[j]=u;}i++;}return SUCCESS;
}
//************************************
// Method:    create_tree
// FullName:  create_tree
// Access:    public
// Returns:   int
// Qualifier:create tree of huffman
// Parameter: HUFF_NODE_PTR * head
//************************************
int create_tree(HUFF_NODE_PTR* head)
{size_t n=256,i,j;HUFF_NODE_PTR temp[256];memset(temp,0,sizeof(temp));for (i = 0,j=0; i < n; i++){if(array_char[i]){temp[j]			=	huff_malloc((unsigned char)i);temp[j]->wight	=	array_char[i];/*temp[j]->code is the code that contain the info of read_file*/temp[j]->code	=	i;huff_pt[i]=temp[j];j++;}}*head=adjusty(temp,j);amounts=j;return SUCCESS;
}//************************************
// Method:    file_write
// FullName:  file_write
// Access:    public
// Returns:   int
// Qualifier:create function
// Parameter: char * file_name
// Parameter: char * file_stream
// Parameter: size_t num
// Parameter: int flags
//************************************
int file_write(char* file_name,FILE* file_inputs)
{FILE* fp=NULL;int counts=0;unsigned char readdata,writedata=0,*TempPoint;char* file_w=file_name;fp=fopen(file_w,"ab+");if(!fp){printf("can`t open file %s and exit FAILURE!\n", file_name);exit(FAILURE);}while(!feof(file_inputs)){if(fread(&readdata,sizeof(unsigned char),1,file_inputs))TempPoint=(unsigned char*)HUFF_DICTIONARY[readdata];while(*TempPoint){writedata=writedata<<1;writedata|=(*TempPoint-'0');TempPoint++;counts++;if(counts==8){fwrite(&writedata,sizeof(unsigned char),1,fp);counts=0;writedata=0;}}}if(counts){writedata<<=(8-counts);fwrite(&writedata,sizeof(unsigned char),1,fp);}writedata=(unsigned char)((8-counts)%8);fwrite(&writedata,sizeof(unsigned char),1,fp);fclose(fp);return SUCCESS;
}//************************************
// Method:    huff_malloc
// FullName:  huff_malloc
// Access:    public
// Returns:   HUFF_NODE_PTR
// Qualifier:
// Parameter: unsigned char i
//************************************
HUFF_NODE_PTR huff_malloc(unsigned char i)
{HUFF_NODE_PTR temp=(HUFF_NODE_PTR)malloc(sizeof(HUFF_NODE));assert (temp!=NULL);temp->code=i;temp->parent=NULL;temp->lchild=NULL;temp->rchild=NULL;temp->wight=0;return temp;
}//************************************
// Method:    adjusty
// FullName:  adjusty
// Access:    public
// Returns:   HUFF_NODE_PTR
// Qualifier:
// Parameter: HUFF_NODE_PTR code[]
// Parameter: size_t n
//************************************
HUFF_NODE_PTR adjusty(HUFF_NODE_PTR code[],size_t n)
{assert (n<=256);int i,j=0,k=0;/* index j replcaethe lest,and index k replace the second*/HUFF_NODE_PTR temp=NULL;while(n){for(i=0; i<n; i++){if(code[k]->wight>code[i]->wight){if(code[j]->wight>code[i]->wight){k=j;j=i;}elsek=i;}}/*finished the merge*/if(j==k){if(n==1)break;k++;i=k;while(i<n){if(code[k]->wight>code[i]->wight)k=i;i++;}}temp=huff_malloc(0);/*merge two child*/temp->lchild=code[j];temp->rchild=code[k];/*child pointer point to parent*/code[j]->parent=temp;code[k]->parent=temp;temp->wight=code[j]->wight+code[k]->wight;if(j<k){code[j]=temp;if(k!=(--n))code[k]=code[n];}else{code[k]=temp;if(j!=(--n))code[j]=code[n];}k=0;j=0;}return temp;
}//************************************
// Method:    decode
// FullName:  decode
// Access:    public
// Returns:   void
// Qualifier:
// Parameter: HUFF_NODE_PTR head
// Parameter: FILE * fp
//************************************
void decode (HUFF_NODE_PTR head,FILE* fp)
{unsigned char read_code,tempcode=0,rewards=0,tp=0;int count=8,model=0;int flags=0;HUFF_NODE_PTR decode_head=head;unsigned char CHINESE[3]= {0,0,0};while(!feof(fp)){backup:count=8;/*get a 8 bits code to find the leaves*/fread(&tempcode,sizeof(unsigned char),1,fp);/*if arrive to last second character you shouldexit now !*/if(feof(fp))break;read_code=tempcode;while(decode_head){/*go to the leave note!,should to decode now*/if(!decode_head->lchild){fread(&rewards,sizeof(unsigned char),1,fp);fread(&tp,sizeof(unsigned char),1,fp);/*arrive to second character*/model++;model%=2;CHINESE[model]=decode_head->code;if(CHINESE[(model-1+2)%2]>0xa0){if(!model)swap_func(&CHINESE[0],&CHINESE[1]);printf("%s",CHINESE);CHINESE[0]=CHINESE[1]=0;}else if (CHINESE[model]<0xa0){printf("%c",CHINESE[model]);}decode_head=head;if(feof(fp)){ungetc((char)tp,fp);ungetc((char)rewards,fp);flags=1;break;}fseek(fp,-2,SEEK_CUR);}/*left child should be 1,and else the opposite*/if(read_code&0x80){decode_head=decode_head->rchild;}elsedecode_head=decode_head->lchild;read_code<<=1;count--;/*if get here means that: a unsigned char temphas been used out and we should start again!*/if(!count)goto backup;}if(flags)break;}assert(count>=rewards);while(count-rewards){if(read_code&0x80){decode_head=decode_head->rchild;}elsedecode_head=decode_head->lchild;read_code<<=1;count--;if(!decode_head->lchild){model++;model%=2;CHINESE[model]=decode_head->code;if(CHINESE[(model-1+2)%2]>0xa0){if(!model)swap_func(&CHINESE[0],&CHINESE[1]);printf("%s",CHINESE);CHINESE[0]=CHINESE[1]=0;}else if (CHINESE[model]<0xa0){printf("%c",CHINESE[model]);}decode_head=head;}}return;
}//************************************
// Method:    swap_func
// FullName:  swap_func
// Access:    public
// Returns:   void
// Qualifier:
// Parameter: unsigned char * A
// Parameter: unsigned char * B
//************************************
void swap_func(unsigned char *A,unsigned char *B)
{unsigned temp=*A;*A=*B;*B=temp;return;
}//************************************
// Method:    write_dictionary
// FullName:  write_dictionary
// Access:    public
// Returns:   void
// Qualifier: write to file keeping message
// of dictionary
// Parameter: char * file_name
//************************************
void write_dictionary(char* file_name)
{int counts=0,length;FILE* fp=fopen(file_name,"ab+");//char* file_w=(char *)malloc(strlen(file_name)+3);assert(fp!=NULL);/*write to logs*//*write the amount of characters*/fwrite(&amounts,sizeof(unsigned char),1,fp);for(; counts<256;){/*if(current dictionary is not null that means you shouldwrite it to dictionary, causing this is a pointer pointingto a series of decodehere we should write the character ,decode,and its length*/if(HUFF_DICTIONARY[counts]){fwrite(&counts,sizeof(unsigned char),1,fp);length=strlen(HUFF_DICTIONARY[counts]);fwrite(&length,sizeof(int),1,fp);fwrite(HUFF_DICTIONARY[counts],sizeof(unsigned char),length,fp);}counts++;}fclose(fp);return ;
}//************************************
// Method:    output
// FullName:  output
// Access:    public
// Returns:   void
// Qualifier:decode and output
// Parameter: char * file_name
//************************************
void output(char* file_name)
{int ch_counts=0,length=0;unsigned char ch_index=0;HUFF_NODE_PTR head_index=NULL;FILE* fp=fopen(file_name,"rb+");assert(fp!=NULL);fread(&ch_counts,sizeof(unsigned char),1,fp);while(ch_counts--){fread(&ch_index,sizeof(unsigned char),1,fp);fread(&length,sizeof(int),1,fp);free(HUFF_DICTIONARY[ch_index]);HUFF_DICTIONARY[ch_index]=(char*)malloc(length+1);memset(HUFF_DICTIONARY[ch_index],0,length+1);fread(HUFF_DICTIONARY[ch_index],sizeof(char),length,fp);}printf("\ndecode start...\n");//create_tree(&head_index);head_index = tree_from_dic(HUFF_DICTIONARY);decode(head_index,fp);printf("\ntranslation has been finished\n");return ;
}void version(void)
{printf("\nCOPYRIGHT @ NEWPLAN IN UESTC\n");printf("CURRENT VERSION IS NEWPLAN.0.1 THANKS FOR SUPPORT US!\n\n");return;
}
void help(void)
{printf("/*********************************************""*********************************\n**	by using huffman method\n""**	NEWPLAN @ UESTC 2014.5\n*******************************""***********************************************/ \n");printf("choose function to operate!\n");printf("FORMAT:\n");printf("NEWPLAN [parameter] [FILE]\n");printf("this is about compress file to a new file with FORMAT : file_name.n \n");printf("parameter:\n");printf("\t-c\t\tcheck for compress file\n");printf("\t-z\t\tcheck for decompress file\n");printf("\t--help\t\tcheck for documents\n");printf("\t--version\tcheck for version\n");return;
}void compress(const char* file_s)
{char* fw=NULL;FILE* file_index=file_open(file_s);fw=(char*)malloc(strlen(file_s)+3);assert ((file_index!=NULL)&&(fw!=NULL));memset(fw,0,strlen(file_s)+3);strcat(fw,file_s);strcat(fw,".n");claculate(file_index);create_dictiony();write_dictionary(fw);fclose(file_index);file_index=file_open(file_s);file_write(fw,file_index);return;
}void decompress_func(const char* file_s)
{char* fw=(char*)malloc(strlen(file_s)+3);assert(fw!=NULL);memset(fw,0,strlen(file_s)+3);strcat(fw,file_s);strcat(fw,".n");output(fw);return;
}HUFF_NODE_PTR tree_from_dic(char** dic_array)
{int cycle=0;char* ch_ptr=NULL;HUFF_NODE_PTR temp=NULL;HUFF_HEADER=huff_malloc(0);for (cycle = 0; cycle < 256; cycle++){if(dic_array[cycle]){temp=HUFF_HEADER;ch_ptr=dic_array[cycle];while(*ch_ptr){if(*ch_ptr=='0'){if(!temp->lchild){temp->lchild=huff_malloc(0);temp->lchild->parent=temp;}temp=temp->lchild;}else{if(!temp->rchild){temp->rchild=huff_malloc(0);temp->rchild->parent=temp;}temp=temp->rchild;}ch_ptr++;}temp->code=cycle;}}return HUFF_HEADER;
}


这篇关于中文压缩和解码程序设计与实现(huffman)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1074748

相关文章

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删