📄 prog4.txt
字号:
#include <stdio.h>
#include <stdlib.h>
#include "error.h"
#include "minheap.h"
#include "hufftree.h"
//prog4.c//
/* function prototypes */
HuffTree SortTree(MinHeap);
int * ReadCharacters(FILE *);
int main(void)
{
int *char_array;
MinHeap mh;
HuffTree temp,ht;
FILE *fp;
int i;char name[15];
/* open the text file */
printf("Enter the file name:");
scanf("%s",name);
fp = fopen(name, "r");
if(fp == NULL)
FatalError("File not found not found!");
}
mh = NewMinHeap();
/* read the data file, counting the number of times each char
occurs in it */
char_array = ReadCharacters(fp);
/* finished with the file, so close it */
fclose(fp);
/* create a temporary HuffTree based upon the frequencies of the
chars read from the file */
for(i = 0; i < MAX_ARRAY; i++)
{
if(char_array[i] != 0)
{
temp = NewHuffTree(i,char_array[i]);
InsertMinHeap(mh,temp);
}
}
/* sorts the HuffTree for optimal size based upon frequencies */
ht = SortTree(mh);
/* output the resulting HuffTree codes to the screen */
OutputHuffCodes(ht);
return 1;
}
/* "sorts" the HuffTree so that characters are only in the leaves */
HuffTree SortTree(MinHeap mh)
{
HuffTree q, p, new;
while(SizeMinHeap(mh) > 1)
{
q = DeleteMinHeap(mh);
p = DeleteMinHeap(mh);
new = JoinHuffTrees(q,p);
InsertMinHeap(mh, new);
}
new = DeleteMinHeap(mh);
}
/* reads the characters from the text file, counting the number of times
each character occurs */
int * ReadCharacters(FILE *fp)
{
int *char_array, i, c;
c = 1;
char_array = malloc(MAX_ARRAY * sizeof(int));
if(char_array == NULL)
{
FatalError("Not enough memory!");
}
for(i = 0; i < MAX_ARRAY; i++)
{
char_array[i] = 0;
}
while(c != EOF)
c = 1;
char_array = malloc(MAX_ARRAY * sizeof(int));
if(char_array == NULL)
{
FatalError("Not enough memory!");
}
for(i = 0; i < MAX_ARRAY; i++)
{
char_array[i] = 0;
}
while(c != EOF)
{ c = fgetc(fp);
char_array[c]++;
}
return char_array;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -