예제 #1
0
bool Encoding::compress(ibstream &inStream, obstream &outStream){
	buildEncodingForInput(inStream);
	int input;
	string code;

	map<int, string>::iterator it;
	outStream.put(mp.size());
	outStream.put('|');
	for (it = mp.begin(); it != mp.end(); it++){
		outStream.put(it->first);
		//cout << it->first << " has the code ";
		for (int i = 0; i < it->second.size(); i++){
			outStream.put(it->second[i]);
			//cout << it->second[i];
		}
		outStream.put('|');
		//cout << endl;
	}

	inStream.rewind();
	string temp;
	int letter;
	int temps;
	for (int i = 0; i < inStream.size(); i++){
		temps = inStream.size();
		input = inStream.get();
		code = mp[input];
		for (int i = 0; i < code.length(); i++){
			temp = code[i];
			outStream.writebit(StringToInteger(temp));
			//cout << code[i];
		}
		//cout << endl;
	}
	outStream.put(_EOF_);
	outStream.close();


	return true;

}
/* Function: compress
 * Usage: compress(infile, outfile);
 * --------------------------------------------------------
 * Main entry point for the Huffman compressor.  Compresses
 * the file whose contents are specified by the input
 * ibstream, then writes the result to outfile. */
void compress(ibstream& infile, obstream& outfile) {
    /* Calculates the frequencies of each character within text */
    Map<ext_char, int> frequenciesTable = getFrequencyTable(infile);

    /* Buffer-vector for cypher tree creation */
    Vector<Node*> vec;
    /* Add nodes for each sumbol and put them to vec */
    buildNodesVector(vec, frequenciesTable);
    /* Main Huffman tree building */
    Node* root = buildEncodingTree(vec);

    /* ENCODE TREE INTO CYPHER FILE HEADER */
    encodeTreeToFileHeader(root, outfile);
    outfile.put(' ');//put some char to divide header from main text cypher

    /* ENCODE FILE MAIN TEXT INTO CYPHER FILE */
    infile.rewind();
    encodeMainTextToFile(infile, root, outfile);

    /* Memory cleaning */
    deleteTree(root);
}