float* constructHistogram (istream& in) { float* histogram = new float[0x100]; uchar c; while (c = in.get(), in) { histogram[c]++; } in.seekg(ios::beg); //in.clear(); cin.clear(istream::eofbit); return histogram; } void usage (char* progname) { cerr << "Usage:\t" << progname << " -e infile outfile\n"; cerr << "\t" << progname << " -d infile outfile\n\n"; cerr << "Use the -e option to encode, and -d to decode.\n"; } int main (int argc, char** argv) { if (argc != 4) { usage(argv[0]); return 1; } ifstream fin(argv[2]); ofstream fout(argv[3]); if (argv[1][1] == 'e') { float* freqs; if (-1 == fin.tellg()) // this file does not support seeking, so use fallback frequencies freqs = fallbackFreqs; else freqs = constructHistogram(fin); HuffmanCoder hc(freqs); if (freqs != fallbackFreqs) delete[] freqs; string text; deque huffman_stream = hc.start(); while (fin) { char buf[1024]; fin.read(buf, sizeof(buf)); int buflen = fin.gcount(); cerr << buflen << endl; string stringbuf(buf, buflen); hc.write(huffman_stream, stringbuf); } hc.flush(huffman_stream, fout); } else if (argv[1][1] == 'd') { HuffmanDecoder dc(fin); fout << dc.decode(); } else { usage(argv[0]); return 1; } }