代码范例
时间: 2023-07-03 18:28:30 浏览: 54
以下是一个简单的C语言实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_FREQ 256
#define MAX_CODE_LEN 100
typedef struct node {
char ch;
int freq;
struct node *left;
struct node *right;
} Node;
Node *nodes[MAX_FREQ];
char codes[MAX_FREQ][MAX_CODE_LEN];
int freqs[MAX_FREQ];
int n_nodes = 0;
int n_codes = 0;
Node *new_node(char ch, int freq, Node *left, Node *right) {
Node *node = (Node*) malloc(sizeof(Node));
node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;
return node;
}
void insert_node(Node *node) {
int i;
for (i = 0; i < n_nodes; i++) {
if (node->freq < nodes[i]->freq) {
break;
}
}
for (int j = n_nodes; j > i; j--) {
nodes[j] = nodes[j - 1];
}
nodes[i] = node;
n_nodes++;
}
Node *pop_node() {
return nodes[--n_nodes];
}
void build_tree() {
while (n_nodes > 1) {
Node *left = pop_node();
Node *right = pop_node();
Node *parent = new_node('\0', left->freq + right->freq, left, right);
insert_node(parent);
}
}
void traverse_tree(Node *node, char *code, int depth) {
if (node->left == NULL && node->right == NULL) {
code[depth] = '\0';
strcpy(codes[n_codes], code);
n_codes++;
} else {
code[depth] = '0';
traverse_tree(node->left, code, depth + 1);
code[depth] = '1';
traverse_tree(node->right, code, depth + 1);
}
}
void encode_file(char *input_file, char *output_file) {
FILE *fp_in = fopen(input_file, "r");
FILE *fp_out = fopen(output_file, "wb");
if (fp_in == NULL || fp_out == NULL) {
printf("Error opening file\n");
exit(1);
}
int freq[MAX_FREQ] = {0};
int ch;
while ((ch = fgetc(fp_in)) != EOF) {
freq[ch]++;
}
for (int i = 0; i < MAX_FREQ; i++) {
if (freq[i] > 0) {
insert_node(new_node(i, freq[i], NULL, NULL));
}
}
build_tree();
char code[MAX_CODE_LEN];
traverse_tree(nodes[0], code, 0);
rewind(fp_in);
int bit_count = 0;
unsigned char buffer = 0;
while ((ch = fgetc(fp_in)) != EOF) {
for (int i = 0; i < n_codes; i++) {
if (codes[i][0] == ch) {
for (int j = 0; j < strlen(codes[i]); j++) {
if (codes[i][j] == '1') {
buffer |= 1 << (7 - bit_count);
}
bit_count++;
if (bit_count == 8) {
fwrite(&buffer, sizeof(unsigned char), 1, fp_out);
buffer = 0;
bit_count = 0;
}
}
break;
}
}
}
if (bit_count > 0) {
fwrite(&buffer, sizeof(unsigned char), 1, fp_out);
}
fclose(fp_in);
fclose(fp_out);
}
int main() {
encode_file("input.txt", "output.bin");
return 0;
}
```
这段代码实现了将给定文本文件编码成哈夫曼编码,并用二进制比特位编码成文本文件的功能。