实现文件中数据的加解密与压缩:将硬盘上的一个文本文件进行加密,比较加密文件和原始文件的大小差别;对加密文件进行解密,比较原始文件和解码文件的内容是否一致。
代码
#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)