📄 block.cpp
字号:
// Created:11-09-98
// By Jeff Connelly
// Example of compressing ComprLibFileIO::source_file blocks, similar to PKZIP's "deflate" algorithm
#include <stdio.h>
#include "comprlib.h"
#include <stdlib.h>
#include <unistd.h>
#include <io.h>
// Help message
const char* help = "Compresses a file in, like PKZIP's deflate\n"
"\tBLOCK input output\n"
"input and output are filenames to open\n"
"\n";
// BLOCK_COUNT specifies number of blocks in the input file
#define BLOCK_COUNT 100
int main(int argc, char* argv[])
{
if (argc != 3)
{
printf (help);
exit (0);
}
FILE* in; // Input and
FILE* out; // output files
FILE* tmp; // Temporary input and
FILE* tout; // output files
register int i = 0;
unsigned int bsize; // Block size for all blocks (all fixed size)
unsigned int csize; // Compressed block size
char* block;
// Open the files and validate them
in = fopen(argv[1], "rb");
out = fopen(argv[2], "wb");
if (!in || !out)
{
printf ("Cannot open file(s)\n");
exit (1);
}
ComprLibFileIO::Set(); // Use file I/O
// 'bsize' will contain the size of each block to make BLOCK_COUNT blocks
bsize = filelength(fileno(in)) / BLOCK_COUNT;
if (!bsize)
{
printf ("File size to small for block size %d\n", BLOCK_COUNT);
exit (2);
}
// The header is a 32-bit unsigned integer containing 'bsize', the size
// of each of the blocks
fwrite (&bsize, 1, sizeof(bsize), out);
while(!feof(in))
{
printf ("\nBlock %d...", i++);
// Allocate the memory and validate
block = (char*)malloc(bsize);
if (!block)
{
printf ("Out of memory\n");
exit (3);
}
// Read 'bsize' bytes into 'block', this is the block
fread (block, bsize, 1, in);
// Write 'block' to a temp file
tmp = tmpfile();
tout = tmpfile();
if (!tmp || !tout)
{
printf ("Cannot open temporary file(s)\n");
exit (4);
}
fwrite (block, bsize, 1, tmp);
// LZSS compress the temp file to the temp output file
ComprLibFileIO::source_file = tmp;
ComprLibFileIO::dest_file = tout;
lzss_encode();
// If the compressed block is larger, don't compress it
csize = filelength(fileno(tout));
if (csize > filelength(fileno(tmp))) // Compressed is larger!
{
// Store uncompressed, '\0' means not compressed
fputc('\0', out);
fwrite(block, bsize, 1, out);
printf ("Larger: %d / %d", bsize, csize);
} else {
// Yes! The compressed size is smaller!
fputc('\001', out);
fread(block, csize, 1, tout);
fwrite(block, csize, 1, out);
printf ("Smaller: %d / %d", bsize, csize);
}
// We are done with the temporary file and block
fclose(tmp);
fclose(tout);
free(block);
}
if (tmp)
fclose(tmp);
fclose(in);
fclose(out);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -