二进制文件处理压缩数据:未使用读取代码段致结果异常的疑问
Hey there! Let's break down why that seemingly useless chunk of code is actually critical to your decompression working correctly.
What That Code Is Actually Doing
First, let's look at the code in question:
unsigned char NRBst[2]; Resfile.read((char *)NRBst, 2 * sizeof(char));
Even though the NRBst array isn't referenced anywhere else after this, the read call is performing a key action: it's advancing your file stream's read pointer by 2 bytes.
In your binary compressed file, those 2 bytes are almost certainly part of the file's header structure—they might be a reserved placeholder, a legacy checksum, a version flag, or just padding added during the compression process. The original code was designed to skip over these bytes to reach the actual compressed data that follows them.
Why Removing It Causes Decompression Failure
When you comment out this code, your file stream's read position never moves past those 2 header bytes. That means all subsequent reads for the compressed data start 2 bytes too early.
Your decompression algorithm expects a specific format of input data (like a valid compressed stream start marker, or correctly aligned byte sequences for the compression method you're using). By feeding it those extra 2 header bytes first, you're giving the decompressor corrupted, misaligned data. It's like trying to read a book starting from the middle of the title page instead of the first chapter—nothing makes sense, so the decompression fails and produces garbage results.
A More Readable Alternative (If You Don't Need Those Bytes)
If those 2 bytes really are unused and only need to be skipped, a clearer way to handle this instead of using an unused array is to directly adjust the file pointer:
Resfile.seekg(2, std::ios::cur); // Move read pointer 2 bytes forward from current position
This makes your intent obvious to anyone reading the code, without relying on a "magic" unused variable.
内容的提问来源于stack exchange,提问作者lena

