void FileCompress::Uncompress(const char* filename) { HuffmanTree ht; int size = 0; //从配置文件中获取字符信息 string filenameconfig = filename; filenameconfig += ".config"; FILE* fout = fopen(filenameconfig.c_str(),"r"); assert(fout); unsigned char ch = fgetc(fout); long long sum = 0; while (!feof(fout)) { _infos[ch]._ch = ch; size++; char num = fgetc(fout); num = fgetc(fout); _infos[ch]._count = num - '0'; sum += _infos[ch]._count; ch = fgetc(fout); ch = fgetc(fout); } fclose(fout); //建树 CharInfo invaild; //ReadConfig(filename, _infos); ht.CreateTree(_infos, size,invaild); //从压缩文件取值遍历 string filenamecom = filename; filenamecom += ".com"; FILE* fin = fopen(filenamecom.c_str(),"r"); assert(fin); string filenameuncom = filename; filenameuncom += ".uncom"; fout = fopen(filenameuncom.c_str(), "w"); assert(fout); HuffmanTreeNode<CharInfo>* temp = ht.GetRoot(); ch = fgetc(fin); int count = 0; unsigned int t = 1; while ( !feof(fin))//sum != 0) { int x = 0; for (int i = 7; i >= 0; i--) { x = ch & (t << 7); if ((char)ch == EOF) { cout << 1; } ch <<= 1; if (x == 0) temp = temp->_left; else if (x == 0x80) temp = temp->_right; if (temp->_left == NULL && temp->_right == NULL) { fputc(temp->_weight._ch, fout); //sum--; cout << temp->_weight._ch; temp = ht.GetRoot(); x = 0; } } ch = fgetc(fin); } fclose(fin); fclose(fout); }
void FileCompress::Compress(const char* filename) { HuffmanTree mh; int size = Get_infos_Com(filename); //建树 CharInfo invaild; mh.CreateTree(_infos, size,invaild); //编码 string code; GenerateHuffmanCode(mh.GetRoot(), code); //配置文件 string filenameConfig = filename; filenameConfig += ".config"; FILE* fout = fopen(filenameConfig.c_str(), "wb"); assert(fout); for (int i = 0; i < 256; i++) { if (_infos[i]._count != 0) { fputc(_infos[i]._ch, fout); fputc(',', fout); fputc(_infos[i]._count+'0',fout); fputc('\n',fout); } } fclose(fout); //WriteConfig(filename); FILE* fin = fopen(filename, "r"); unsigned char ch = fgetc(fin); string filenamecom = filename; filenamecom += ".com"; fout = fopen(filenamecom.c_str(), "w+"); assert(fout); unsigned char value = 0; int pos = 7; while (!feof(fin)) { if (ch == '\r') { ch = fgetc(fout); if (ch != '\n') { fseek(fout, -1, SEEK_CUR); } } string& code = _infos[ch].code; int d = 0; for (int i = 0; i < code.size(); i++) { value <<= 1; if ((code[i] - '0') & (1)) { value |= 1; } else { value |= 0; d = 1; } pos--; if (pos == -1) { fputc(value, fout); if (d = 0) { cout << 1; } value = 0; d = 0; pos = 7; } } ch = fgetc(fin); } if (pos != -1) { for (int i = 0; i <= pos; i++) { value <<= 1; } fputc(value, fout); } fclose(fin); fclose(fout); }