因此,我需要先读取一个 unicode 文件,然后使用 Huffman 算法对其进行转换(有效压缩它)并将其写入一个新文件。
unicode 的原因是特殊字符,如连字符 - 较长的破折号和其他 - 没有 unicode,使用 ifstream/ofstream 和 unsigned char 读写将连字符转换为 3 个单独的字符,当我想解压缩文件时,它会添加以前的字符不在那里。
现在,我使用 std::wifstream 和 std::wofstream 来执行此操作,如下所示:
size_t bitsNum = 65536;
std::wifstream in("a", std::ios::binary);
std::wofstream out("b", std::ios::binary);
void compress(std::wifstream &in, std::wofstream &out) {
in.clear();
in.seekg(0);
uint64_t size = 0;
for (wchar_t i = 0; i < nodes.size(); ++i) {
size += nodes.at(i).probability * codes.at(nodes.at(i).value).length;
}
std::cout << "Final size: " << size << '\n';
wchar_t c, w = 0, length, lengthW = 0;
std::bitset<bitsNum> bits;
while (!in.eof() && in.good()) {
c = in.get();
bits = codes.at(c).bits;
length = codes.at(c).length;
for (wchar_t i = 0; i < length; ++i) {
if (lengthW == 16) {
lengthW = 0;
out << w;
w = 0;
}
w <<= 1;
w |= bits.test(length - i - 1) & 1;
++lengthW;
}
}
if (lengthW == 16) {
lengthW = 0;
out << w;
w = 0;
}
else if (lengthW) {
w <<= 16 - lengthW;
out << w;
w = 0;
}
out.flush();
if (DECOMPRESS) decompress();
}
节点对象包含从文件中读取的每个字符的频率分布,而代码对象包含必须转换的每个字符的位代码。
这导致了这样一个事实,即我可以毫无问题地读取文件,但是当我写回新位时,没有任何内容被写入文件。
我尝试灌输一个语言环境,但没有帮助,还设置了一个全局语言环境。
除了将 wchar_t 导入 wofstream 之外,我还尝试使用 .put() 函数和 .write() - 这里没有运气。
关于什么可能是错的任何想法?
PS:我只能使用没有扩展的标准 c++17。
谢谢!