哈弗曼编码

 1 /*************************
 2 程序功能:读取一个文本文件的内容并计算里面各种字符出现的次数
 3 
 4 *************************/
 5 #include<stdio.h>
 6 #include<stdlib.h>
 7 #define MAXLEN 10000
 8 
 9 //结构体用来存放字符的信息
10 struct ChNode
11 {
12    int ascii;
13    char ch;
14    int count;
15 };
16 typedef struct ChNode ChNode;
17 
18 //声明计算字符出现次数的函数
19 void Count_Times(char text[],ChNode freq[]);
20 int main()
21 {
22     ChNode freq[256];
23     char text[MAXLEN];
24 
25     Count_Times(text,freq);
26     return 0;
27 }
28 void Count_Times(char text[],ChNode freq[])
29 {
30     FILE *fp; //指针指向文件
31     char chtmp;
32     int i;
33 
34     //给数组初始化
35     for(i=0;i<256;i++)
36     {
37         freq[i].ascii=i;
38         freq[i].ch=(char)i;
39         freq[i].count=0;
40     }
41 
42     i=0;
43     fp=fopen("a.txt","r");
44     //读取文件内容并计算字符出现的次数
45     while(!feof(fp))
46     {
47         fscanf(fp,"%c",&chtmp);
48         text[i++]=chtmp;
49         freq[chtmp].count++;
50     }
51     fclose(fp);
52 
53     //将数组信息输出到另一个文件里
54     fp=fopen("freq.txt","w");//以a++形式打开文件
55     for(i=0;i<256;i++)
56         fprintf(fp,"%d   %c   %d
",freq[i].ascii,freq[i].ch,freq[i].count);
57     fclose(fp);
58 
59 }

代码43--51行代码用来统计字符出现的次数,此种方法会使得最后一个字符多读一次才能关闭指针,因此最后一个字符会多一次

应改为:

 1 i=0;
 2     fp=fopen("a.txt","r");
 3     fscanf(fp,"%c",&chtmp);
 4     while(!feof(fp))
 5     {
 6         text[i++]=chtmp;
 7         freq[chtmp].count++;
 8         fscanf(fp,"%c",&chtmp);
 9     }
10     fclose(fp);

将数组信息写入文件时应用“w”,而不用“a+”,后者会不断叠加。

原文地址:https://www.cnblogs.com/banshaohuan/p/4459189.html