📄 huff.cpp
字号:
/*
huff.cpp
Huffman coding examples
*/
#include <stdio.h>
#include <compress.h>
int main(int argc,char *argv[])
{
STREAM *in, *out;
int compress;
if(argc != 4) {
// display usage
printusage:
fprintf(stderr,"USAGE: HUFF [-c|d] <infile> <outfile>\n");
fprintf(stderr,"Where -c is compress, -d is decompress\n");
return 1;
}
// test flag if it is -c or -d
if(argv[1][0] == '-') {
if(argv[1][1] == 'c') compress = 1;
else if(argv[1][1] == 'd') compress = 0;
else goto printusage;
} else goto printusage;
in = stream_open(argv[2],"rb"); // open input file
if(!in) {
fprintf(stderr,"Can't open file `%s'.\n",argv[2]);
return 1;
}
out = stream_open(argv[3],"wb"); // open input file
if(!in) {
stream_close(in);
fprintf(stderr,"Can't open file `%s'.\n",argv[3]);
return 1;
}
HuffTable tab[257]; // make a table of 257 entries since there are 256
// characters in a byte + 1 EOF code
int i, ch;
if(compress) { // if compressing
for(i = 0; i < 257; i++) { // initialize the huffman table
tab[i].code = i;
tab[i].len = 0;
}
// build a table of frequency counts
while((ch = stream_getc(in)) != EOF) tab[ch].len++;
tab[256].len = 1; // EOF code has a count of 1
CalculateMinimumRedundancy(tab,257); // calculate minimum bits to encode
BuildHuffTable(tab,257); // Generate the huff codes
WriteHuffmanHeader(out,tab,257,0); // write huffman header
stream_seek(in,0L,SEEK_SET); // rewind stream
while((ch = stream_getc(in)) != EOF)
WriteHuffmanCode(out,tab[ch]); // Write huffman code
WriteHuffmanCode(out,tab[256]); // always write EOF code
stream_flush_write_bufferr(out); // flush output buffer
} else { // if decomrpession
// read the huffman header, we assume that the header is always 257 entries
// so we pass NULL to the nLit parameter
ReadHuffmanHeader(in,tab,NULL,NULL,NULL);
HuffLookup *lookup; // lookup table for decompress
lookup = BuildHuffmanLookupTable(tab,257); // generate lookup table
if(!lookup) {
fprintf(stderr,"Out of memory.\n");
stream_close(in);
stream_close(out);
return 1;
}
ch = 0;
for(;;) {
ch = FetchHuffmanCode(in,lookup); // fetch code
if(ch == 256 || stream_eof(in)) break;
stream_putc(ch,out); // output code
}
}
stream_close(in);
stream_close(out);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -