ZBLOG

#include #include #include #include #include #include using namespace std; // 定义节点结构体 struct Node { char ch; int freq; Node *left, *right; Node(char c, int f) : ch(c...

我看到你的代码中没有明确处理文本文件的字符编码方式,默认情况下使用 ASCII 编码。如果输入文件中包含非 ASCII 字符,那么解压后的文件可能会显示乱码。

为了解决这个问题,你可以在读取和写入文件时指定字符编码方式。例如,在压缩文件部分修改如下:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <unordered_map>
  4. #include <string>
  5. #include <vector>
  6. #include <queue>
  7. using namespace std;
  8. // ...
  9. void compressFile(string inputFile, string outputFile) {
  10. // 读取输入文件计算每个字符出现的频率
  11. ifstream ifs(inputFile, ios::binary);
  12. unordered_map<char, int> freqMap;
  13. unsigned char ch;
  14. while (ifs.get(reinterpret_cast<char&>(ch))) {
  15. ++freqMap[ch];
  16. }
  17. ifs.close();
  18. // 构建Huffman树和反向编码表
  19. Node* root = buildHuffmanTree(freqMap);
  20. unordered_map<char, string> codeMap;
  21. generateCode(root, "", codeMap);
  22. // 写入压缩数据到输出文件
  23. ofstream ofs(outputFile, ios::binary);
  24. for (const auto& pair : freqMap) {
  25. ofs << pair.first << " " << pair.second << endl;
  26. }
  27. ifs.open(inputFile, ios::binary);
  28. while (ifs.get(reinterpret_cast<char&>(ch))) {
  29. string code = codeMap[ch];
  30. for (const auto& bit : code) {
  31. buf |= (bit - '0') << (7 - pos);
  32. ++pos;
  33. if (pos == 8) {
  34. ofs.put(buf);
  35. buf = 0;
  36. pos = 0;
  37. }
  38. }
  39. }
  40. if (pos > 0) {
  41. ofs.put(buf);
  42. }
  43. ifs.close();
  44. ofs.close();
  45. cout << "文件压缩完成!压缩后的文件名为:" << outputFile << endl;
  46. }
  47. // ...
  48. int main() {
  49. string inputFile = "input.txt";
  50. string compressedFile = "compressed.bin";
  51. string decompressedFile = "decompressed.txt";
  52. // 压缩文件
  53. compressFile(inputFile, compressedFile);
  54. // 解压缩文件
  55. decompressFile(compressedFile, decompressedFile);
  56. return 0;
  57. }

在解压文件部分也进行类似修改:

  1. void decompressFile(string inputFile, string outputFile) {
  2. // ...
  3. while (ifs.get(reinterpret_cast<char&>(ch))) {
  4. for (int i = 7; i >= 0; --i) {
  5. bool bit = (ch >> i) & 1;
  6. cur = bit ? cur->right : cur->left;
  7. if (!cur->left && !cur->right) {
  8. ofs.put(cur->ch);
  9. cur = root;
  10. }
  11. }
  12. }
  13. ifs.close();
  14. ofs.close();
  15. cout << "文件解压完成!解压后的文件名为:" << outputFile << endl;
  16. }

这样可以确保正确地处理文本中的字符编码,以避免出现乱码。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10123

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?