赫夫曼编码-C语言

实现文件中数据的加解密与压缩:将硬盘上的一个文本文件进行加密,比较加密文件和原始文件的大小差别;对加密文件进行解密,比较原始文件和解码文件的内容是否一致。

代码

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
typedef struct node* LIST;
typedef struct node* TREE;
struct node
{
   
	int high; //高位ascll
	int low; //判断是否是中文,低位
	int weight;
	int code_index; //编码指针
	char code[100]; //编码数组
	TREE Left;
	TREE Right;
	LIST NEXT;
};
void insert(LIST head, LIST tmp);
LIST find_and_insert(LIST head, LIST tmp);
void output(LIST head);
LIST init_LIST(int high, int low, int weight);
TREE tree_node_init(int high, int low, int weight);
TREE build_tree(LIST head);
void print_huffman_pre(TREE Tree, int flag);
void update_tree(TREE Tree);
void save_file(TREE* a, int right, TREE Tree);
void to_free_tree(TREE Tree);
void to_free_list(LIST head);
void coding(TREE Tree);
void decoding();
TREE queue[1000];
int queue_index = 0;
int sum_bit_coding = 0;
int sum_bit_decoding = 0;
char file_in[100] = "D:\\file.txt";
char file_out[100];
void init_main();
void update_file_out(char file_in[])
{
   
	int i;
	for (i = strlen(file_in) - 1; i >= 0; i--)
		if (file_in[i] == '\\')
			break;
	int j;
	for (j = 0; j <= i; j++)
		file_out[j] = file_in[j];
}
int main()
{
   
	init_main();
	return 0;
}
void init_main()
{
   
	LIST head = init_LIST(0, 0, 0);
	FILE* P;
	while (1)
	{
   
		printf("为了结果的准确性,请输入GBK格式的txt文件\n");
		printf("请输入需要执行的文件及路径\n例如\nD:\\file.txt\n");
		gets(file_in);
		fopen_s(&P,file_in, "r");
		if (P == NULL)
		{
   
			printf("文件打开失败\n请重新输入\n");
			continue;
		}
		else
		{
   
			printf("打开成功\n");
			break;
		}
	}
	update_file_out(file_in);
	int ch;
	while ((ch = fgetc(P)) != EOF)
	{
   
		LIST tmp = init_LIST(ch, -1, 1);
		if (ch > 128)
			tmp->low = fgetc(P);
		insert(head, find_and_insert(head, tmp));
	}
	TREE Tree = build_tree(head);
	coding(Tree);
	print_huffman_pre(Tree->NEXT, 0);
	update_tree(Tree)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鷇韩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值