📄 compress.cpp
字号:
#include <iostream>
#include <stdlib.h>
using namespace std;
int total;
int root_pos;
//Huffman树的节点结构
typedef struct
{
unsigned long weight;
short left, right, parent;
unsigned short bit_code; // max 16 bits code
short code_length;
} hufnode;
hufnode huftree[511];
FILE *infile, *outfile;
char *infile_name;
char outfile_name[20];
int main(int argc, char *argv[])
{
infile_name = argv[1]; //打开文件
strcpy(outfile_name, argv[2]);
if ((infile=fopen(infile_name, "rb")) == NULL)
{
printf("Unable to open input file %s.\n", infile_name);
return 1;
}
while (!feof(infile)) //统计字符的出现次数
{
unsigned char c = fgetc(infile);
if (feof(infile))
continue;
++total;
++huftree[c].weight;
}
fclose(infile);
void create_code(short i ) ;
if ((outfile=fopen(outfile_name, "wb")) == NULL) //写头部格式信息
{
printf("Unable to create %s.\n", outfile_name);
return 1;
}
fwrite((void *)infile_name, sizeof(char),20,outfile);
fwrite((void *)&total, sizeof(long),1,outfile);
fwrite((void *)&root_pos, sizeof(short),1,outfile);
fwrite((void *)&huftree, sizeof(hufnode),511,outfile);
return 0;
void output_bits(unsigned int bit_code, int code_length);
system("PAUSE");
return 0;
}
void create_code(short i ) //构建字符的Huffman编码
{
short current = i;
short parent = huftree[i].parent;
unsigned short code_length = 0;
short code = 0;
while(parent)
{
code_length++;
if(huftree[parent].left == current) // left 1, right 0
code |= 1<<(code_length-1);
current = parent;
parent = huftree[current].parent;
}
huftree[i].code_length = code_length;
huftree[i].bit_code = code;
}
void output_bits(unsigned int bit_code, int code_length) //输出Huffman编码
{
static unsigned char buffer = 0;
static unsigned char bits_used = 0;
bit_code <<= (16 - code_length);
for(short i=0; i<code_length; i++)
{
buffer <<= 1;
buffer |= ((bit_code & 0x8000) !=0);
bit_code <<= 1;
bits_used++;
if(bits_used == 8)
{ fputc(buffer,outfile);
bits_used = 0;
buffer = 0;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -