哈夫曼树文件压缩c语言
时间: 2023-12-07 14:38:57 浏览: 99
以下是使用C语言实现哈夫曼树文件压缩的步骤:
1.读取文件并统计每个字符出现的次数。
```c
FILE *fp;
char ch;
int freq[256] = {0};
fp = fopen("filename.txt", "r");
while((ch = fgetc(fp)) != EOF) {
freq[ch]++;
}
fclose(fp);
```
2.构建哈夫曼树。
```c
struct node {
int freq;
char data;
struct node *left, *right;
};
struct node *newNode(int freq, char data) {
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->freq = freq;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
struct node *buildHuffmanTree(int freq[]) {
struct node *left, *right, *top;
priority_queue<node*, vector<node*>, compare> minHeap;
for(int i=0; i<256; i++) {
if(freq[i] != 0) {
minHeap.push(newNode(freq[i], i));
}
}
while(minHeap.size() != 1) {
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
top = newNode(left->freq + right->freq, '$');
top->left = left;
top->right = right;
minHeap.push(top);
}
return minHeap.top();
}
```
3.生成哈夫曼编码。
```c
void generateHuffmanCode(struct node *root, string str, unordered_map<char, string> &huffmanCode) {
if(!root) {
return;
}
if(root->data != '$') {
huffmanCode[root->data] = str;
}
generateHuffmanCode(root->left, str + "0", huffmanCode);
generateHuffmanCode(root->right, str + "1", huffmanCode);
}
```
4.将哈夫曼编码写入文件。
```c
fp = fopen("compressed_file.bin", "wb");
for(int i=0; i<strlen(original_file); i++) {
fwrite(huffmanCode[original_file[i]].c_str(), sizeof(char), huffmanCode[original_file[i]].size(), fp);
}
fclose(fp);
```
5.解压缩文件。
```c
fp = fopen("compressed_file.bin", "rb");
while((ch = fgetc(fp)) != EOF) {
str += ch;
for(auto i: huffmanCode) {
if(str == i.second) {
decompressed_file += i.first;
str = "";
}
}
}
fclose(fp);
```
6.计算压缩率。
```c
double compressionRatio = (double)compressedFileSize / originalFileSize;
```
7.比较解压文件是否与原文件内容一致。
```c
if(original_file == decompressed_file) {
printf("Decompressed file is same as original file.\n");
} else {
printf("Decompressed file is not same as original file.\n");
}
```
阅读全文