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 字符,那么解压后的文件可能会显示乱码。

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

#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <queue>

using namespace std;

// ...

void compressFile(string inputFile, string outputFile) {
    // 读取输入文件计算每个字符出现的频率
    ifstream ifs(inputFile, ios::binary);
    unordered_map<char, int> freqMap;
    unsigned char ch;
    while (ifs.get(reinterpret_cast<char&>(ch))) {
        ++freqMap[ch];
    }
    ifs.close();

    // 构建Huffman树和反向编码表
    Node* root = buildHuffmanTree(freqMap);
    unordered_map<char, string> codeMap;
    generateCode(root, "", codeMap);

    // 写入压缩数据到输出文件
    ofstream ofs(outputFile, ios::binary);
    
    for (const auto& pair : freqMap) {
        ofs << pair.first << " " << pair.second << endl;
    }
    
    ifs.open(inputFile, ios::binary);
    
   while (ifs.get(reinterpret_cast<char&>(ch))) { 
        string code = codeMap[ch];
        for (const auto& bit : code) {
            buf |= (bit - '0') << (7 - pos);
            ++pos;
            if (pos == 8) {
                ofs.put(buf);
                buf = 0;
                pos = 0;
            }
        }
    }
    if (pos > 0) {
        ofs.put(buf);
    }
    
    ifs.close();
    ofs.close();

    cout << "文件压缩完成!压缩后的文件名为:" << outputFile << endl;
}

// ...

int main() {
    string inputFile = "input.txt";
    string compressedFile = "compressed.bin";
    string decompressedFile = "decompressed.txt";

    // 压缩文件
    compressFile(inputFile, compressedFile);

    // 解压缩文件
    decompressFile(compressedFile, decompressedFile);

    return 0;
}

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

void decompressFile(string inputFile, string outputFile) {
   // ...
    
   while (ifs.get(reinterpret_cast<char&>(ch))) {
        for (int i = 7; i >= 0; --i) {
            bool bit = (ch >> i) & 1;
            cur = bit ? cur->right : cur->left;
            if (!cur->left && !cur->right) {
                ofs.put(cur->ch);
                cur = root;
            }
        }
   }

   ifs.close();
   ofs.close();

   cout << "文件解压完成!解压后的文件名为:" << outputFile << endl;
}

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?