如何处理文件解压中的剩余位

问题描述 投票:0回答:1

我正在创建一个文件压缩和解压,我不知道解压时如何处理剩余的位。

例如,我有 63 位,由于字节 = 8 位,63 % 8 = 7 仍然有 7 位。现在,每当我解压缩文件时,它都会缺少字符。

这是我的代码:

    Node* root = head->node; // Save the root of the Huffman tree
    Node* current = root;    // Initialize the current node

    char byte; // Read bytes for decompression
    while (compressedFileStream.get(byte)) {
        for (int i = 7; i >= 0; i--) {
            if (compressedFileStream.eof()) {
                break; // Break out of the loop if end of file is reached
            }
            // Traverse the tree based on each bit in the byte
            char bit = (byte & (1 << i)) ? '1' : '0';

            if (bit == '0') {
                current = current->left;
            }
            else if (bit == '1') {
                current = current->right;
            }

            if (current->left == NULL && current->right == NULL) {
                decompressedFile << current->character;
                current = root; // Reset current to the root for the next character
            }
        }
    } 

我应该怎样做才能解压我的压缩文件而不丢失字符。

c++ huffman-code
1个回答
0
投票

您的代码当前执行以下操作:

  1. 读取一个字节(它会为您提供一个要解压缩的值+在文件中前进光标)。
  2. 逐一处理位,首先检查是否到达文件末尾。

我发现了一些问题:

  • if (compressedFileStream.eof())
    放入
    for
    循环中看起来就像您希望文件在字节中间结束。这种情况不会发生。
    而且,一旦你完成了测试,只有在读取文件后再次进行测试才有意义:如果你不读取任何内容,则它返回的值不会改变。
  • 就像我上面所说的,读取有效字节后要做的第一件事是测试是否尚未到达文件末尾。在最后一个字节,您在处理任何内容之前退出循环。
    如果你成功读取了一个字节,你就知道它是有效的;因此,在读取下一个字节之前进行测试会更有意义。
考虑到这一点,似乎您所要做的就是在

for

 循环之后推动测试:

Node* root = head->node; // Save the root of the Huffman tree Node* current = root; // Initialize the current node char byte; // Read bytes for decompression while (compressedFileStream.get(byte)) { for (int i = 7; i >= 0; i--) { // Traverse the tree based on each bit in the byte char bit = (byte & (1 << i)) ? '1' : '0'; if (bit == '0') { current = current->left; } else if (bit == '1') { current = current->right; } if (current->left == NULL && current->right == NULL) { decompressedFile << current->character; current = root; // Reset current to the root for the next character } } if (compressedFileStream.eof()) { break; // Break out of the loop if end of file is reached } } // Close the file / free resources here.
    
© www.soinside.com 2019 - 2024. All rights reserved.