csdn_liang2015
csdn_liang2015
2016-01-11 10:20
采纳率: 0%
浏览 1.8k

霍夫曼树程序,输入字符串统计字符出现次数并译码。请问如何改成从文件读入字符串?

//生成HuffmanCode文件的两个函数
void HuffmanEncoding(HuffmanTree HT,HuffmanCode HC){//根据HuffmanTreeHT求HuffmanCode表HC
int c,p,i;
char cd[n];
int start;
cd[num] = '\0';
for(i = 1;i <= num;i++){
start = num;
c = i;
while((p = HT[c].parent) > 0){
cd[--start] = (HT[p].lchild == c)?'0':'1';
c = p;
}
strcpy(HC[i].bits,&cd[start]);
HC[i].len = num - start;
}
}

void coding(HuffmanCode HC,char *str){//对所代表的字符串进行编码,并写入文件
int i,j;
FILE *fp;
fp=fopen("codefile.txt","w");
while(*str){
for(i = 1;i <= num;i++){
if(HC[i].ch == *str){
for(j = 0;j < HC[i].len;j++)
fputc(HC[i].bits[j],fp);
break;
}
}str++;
}fclose(fp);
}
//电文的译码
char * decode(HuffmanCode HC){
FILE *fp;
char str[254];
char *p;
static char cd[n+1];
int i,j,k = 0,cjs;
fp = fopen("codefile.txt","r");
while(!feof(fp)){
cjs = 0;
for(i = 0;i < num&&cjs == 0&&!feof(fp);i++){
cd[i] = ' ';
cd[i+1] = '\0';
cd[i] = fgetc(fp);
for(j = 1;j <= num;j++){
if(strcmp(HC[j].bits,cd) == 0){
str[k] = HC[j].ch;
k++;
cjs = 1;
break;
}
}
}
}
str[k] = '\0';
p = str;
return p;
}
//测试主控函数
void main(){
char st[254],*s,str[27];
int cn[27];
HuffmanTree HT;
HuffmanCode HC;
printf("输入需要编码的字符串(假设均为大写字母):\n");
gets(st);
num = jsq(st,cn,str);//统计字符的种类及各类字符出现的频率
CreHuffmanTree(HT,HC,cn,str);//建立赫夫曼树
HuffmanEncoding(HT,HC);//生成赫夫曼编码
coding(HC,st);//建立电文赫夫曼编码文件
s = decode(HC);//读编码文件译码
printf("译码后的字符串:%s\n",s);//输出译码后的字符串
printf("字符串长度:%d\n",strlen(s));
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • finalspring
    finalspring 2016-01-11 10:25

    c语言读取txt文件命令

    点赞 评论
  • qq_27183003
    ysuwood 2016-01-11 10:58

    在项目目录下建一个1.txt文件存放字符串,然后运行。

     #include <stdio.h>
    void main(){
        char st[254],*s,str[27];
        int cn[27];
        HuffmanTree HT;
        HuffmanCode HC;
    //-------------------------------------
        FILE *fp=NULL;
        fp=fopen("1.txt","r");
        if(NULL==fp)
        {
            printf("1.txt打开失败!\n");
            return ;
        }
        fscanf(fp,"%s",st);
        fclose(fp);
    //-------------------------------------
    
        //printf("输入需要编码的字符串(假设均为大写字母):\n");
        //gets(st);
        num = jsq(st,cn,str);//统计字符的种类及各类字符出现的频率
        CreHuffmanTree(HT,HC,cn,str);//建立赫夫曼树
        HuffmanEncoding(HT,HC);//生成赫夫曼编码
        coding(HC,st);//建立电文赫夫曼编码文件
        s = decode(HC);//读编码文件译码
        printf("译码后的字符串:%s\n",s);//输出译码后的字符串
        printf("字符串长度:%d\n",strlen(s));
    }
    
    
    点赞 评论

相关推荐