Viewing file: c/huffman1/huffman1.cpp | Back to directory listing
Author: Loren Segal | Last modified: February 20 2006 07:00 pm | Download

#include "huffman.h"
using namespace std;
 
const int BUFSIZE = 524288;
 
struct zipHeaderInfo
{
	char file_type[4];
	unsigned short numFiles;
};
 
struct fileHeaderInfo
{
	char filename[10];
	unsigned short numSegments;
};
 
struct segmentHeaderInfo
{
	unsigned int totalBitLength;
	unsigned char charsetSize;
	unsigned char bitCompression;
};
 
int main(int argc, char **argv)
{
	char *filename = new char[256];
	zipHeaderInfo head;
 
	head.file_type[0] = 'J'; head.file_type[1] = 'Z';
	head.file_type[2] = 'I'; head.file_type[3] = 'P';
	head.numFiles = 1;
 
	cout << "Enter a filename: ";
	cin >> filename;
 
	ofstream out;
	out.open("out.jzip.txt", ios::binary | ios::trunc | ios::out);
 
	// write zip header info
	out.write((const char *)&head, sizeof(zipHeaderInfo));
 
	for (int i = 0; i < head.numFiles; i++)
	{
		ifstream in(filename);
		segmentHeaderInfo seg;
		fileHeaderInfo fHeader;
 
		if (!in.is_open())
		{
			cout << "Invalid filename." << endl;
			continue;
		}
 
		// get file size
		in.seekg(0, ios::end);
		fHeader.numSegments = (((int)in.tellg()-1) / BUFSIZE) + 1;
		in.seekg(0, ios::beg);
 
		strcpy(fHeader.filename, filename);
 
		cout << "File header info" << endl;
		cout << "================" << endl;
		cout << "Filename: " << fHeader.filename << endl;
		cout << "Number of segments: " << fHeader.numSegments << endl << endl;
		
		// write file header info
		out.write((const char *)&fHeader, sizeof(fileHeaderInfo));
 
		double c = 0;
		while (!in.eof())
		{
			char buffer[BUFSIZE+1] = {0};
			CompressionSet *zip = new CompressionSet();
			c++;
			// read segment and create charset
			in.read(buffer, BUFSIZE);
//			cout << buffer << endl;
//			cout << setprecision(2) << (c / fHeader.numSegments) * 100 << "%" << endl;
			seg.bitCompression = 1;
			zip->makeCharset(buffer, BUFSIZE, seg.bitCompression);
			seg.charsetSize = zip->numUniqueChars;
			seg.totalBitLength = zip->getTotalBitLength(buffer, BUFSIZE);
		
			// write segment data
			out.write((const char *)&seg, sizeof(seg));
			out.write((const char *)zip->bitCodeList, sizeof(BitCodeInfo) * zip->numUniqueChars);
			out.write((const char *)zip->CompressedString(buffer, BUFSIZE), seg.totalBitLength);
 
			cout << "Segment " << c << " info" << endl;
			cout << "========================" << endl;
			cout << "Charset size: " << seg.charsetSize << endl;
			cout << "Total length: " << seg.totalBitLength << endl;
			cout << "Bit compression: " << seg.bitCompression << endl << endl;
 
			delete zip;
		}
		in.close();
	}
	out.close();
	
	return 0;
}