字典压缩编码器

来源:互联网 发布:联合网络通信 编辑:程序博客网 时间:2024/06/06 05:47
#include<stdio.h>#include<iostream.h>#include<string.h>#include<stdlib.h>#define dictlength 1000#define dictput 3void cover(char *p,char c){memset(p,'\0',sizeof(p));p[0]=c;p[1]='\0';}void add(char *p,char c,int len){*(p+len)=c;*(p+len+1)='\0';}void main (){char *sBuf,dict[dictlength][100]={0};char point[100]={0},nextSymbol;int loc=0,dictlen=177,i,found,find;char a[100]={0};
for(i=1;i<=176;i++)cover(dict[i],i);
//读取文档FILE *fp=fopen("ihave.txt","r+");if(fp==NULL)printf("no file!\n");//elseprintf("success!\n");fseek(fp,0,SEEK_END); //把指针移动到文件的结尾 ,获取文件长度int length=ftell(fp);sBuf=new char[length+1];rewind(fp);fread(sBuf,1,length,fp); //读文件sBuf[length-1]='\0'; //把读到的文件最后一位 写为0 要不然系统会一直寻找到0后才结束fclose(fp);//获取文件指针FILE *pFile = fopen("1.txt", "wb"); // 文件打开方式 如果原来有内容也会销毁//向文件写数据nextSymbol=sBuf[0];while(dictlen<dictlength){nextSymbol=sBuf[loc];i=0;found=0;do{if(strcmp(point,dict[i])==0){found=1;add(point,nextSymbol,strlen(point));break;}i++;}while(i<=dictlen);if(found==0){itoa(dictlen,a,10);fwrite(a, 1,dictput, pFile);/*fwrite ("hello", //要输入的文字 1,//文字每一项的大小 以为这里是字符型的 就设置为1 如果是汉字就设置为4 strlen("hello"), //单元个数 我们也可以直接写5 pFile);//我们刚刚获得到的地址 */strcpy(dict[dictlen],point);dictlen++;cover(point,nextSymbol);}loc++;}while(loc<=(length-159)){cover(point,sBuf[loc]);i=0;find=-1;while(i<dictlength){if(strcmp(point,dict[i])==0){loc++;nextSymbol=sBuf[loc];add(point,nextSymbol,strlen(point));find=i;}i++;}if(find==-1)fwrite("???",1,dictput,pFile);else{itoa(find,a,10);fwrite(a,1,dictput,pFile);}loc++;}fclose(pFile); //告诉系统我们文件写完了数据更新,但是我们要要重新打开才能在写fflush(pFile);//数据刷新 数据立即更新}

0 0
原创粉丝点击