从文件输出原始字节时,第一个字节已损坏

Outputting raw bytes from a file, first byte is corrupted

本文关键字:字节 第一个 已损坏 输出 原始 文件      更新时间:2023-10-16

所以我写了一个小程序,将文件的内容读入char数组(因为fstream似乎只支持char指针)。我想做的是将原始字节发送到控制台。AFAIK char 是 8 位数据类型,因此不应太难。但是,如果我只打印数组的成员,我会得到与 ASCII 值对应的字符,所以我使用的是静态强制转换。这工作正常,除了第一个字节似乎没有正确转换。我正在使用 PNG 文件作为测试.bin文件。PNG 文件始终以字节序列 137,80,78,71,13,10,26,10 开头。但是,第一个字节打印不正确。我有一种感觉,它必须与值超过 127 做一些事情。但是,我无法将读取缓冲区数据类型更改为其他任何类型(例如无符号字符或无符号短整型),因为来自 fstream 的 foo.read() 仅支持 char 目标缓冲区。如何让 fstream 将原始字节读取为可用的无符号类型?

我的代码:

#include <iostream>
#include <fstream>
#include <sys/stat.h>
#define filename "test.bin"
void pause(){
    std::string dummy;
    std::cout << "Press enter to continue...";
    std::getline(std::cin, dummy);
}

int main(int argc, char** argv) {
    using std::cout;
    using std::endl;
    using std::cin;
    // opening file
    std::ifstream fin(filename, std::ios::in | std::ios::binary);
    if (!fin.is_open()) {
       cout << "error: open file for input failed!" << endl;
       pause();
       abort();
    }
    //getting the size of the file
    struct stat statresults;
    if (stat(filename, &statresults) == 0){
        cout<<"File size:"<<statresults.st_size<<endl;
    }
    else{
        cout<<"Error determining file size."<<endl;
        pause();
        abort();
    }
    //setting up read buffer and reading the entire file into the buffer
    char* rBuffer = new char[statresults.st_size];
    fin.read(rBuffer, statresults.st_size);
    //print the first 8 bytes
    int i=0;
    for(i;i<8;i++) {
        cout<<static_cast<unsigned short>(rBuffer[i])<<";";
    }

    pause();
    fin.clear();
    fin.close();
    delete [] rBuffer;
    pause();
    return 0;
}

-119 有符号是 137 无符号(二进制都是 1000 1001)。
这被符号扩展到短 1111 1111 1000 1001,即 65,417 个无符号。
我假设这就是你所看到的价值。

读入无符号缓冲区:

unsigned char* rBuffer = new unsigned char[statresults.st_size];
fin.read(reinterpret_cast<char*>(rBuffer), statresults.st_size);

尝试 fin.read() 以外的其他方法怎么样?

而不是:

char* rBuffer = new char[statresults.st_size];
fin.read(rBuffer, statresults.st_size);

您可以使用:

unsigned char* rBuffer = new unsigned char[statresults.st_size];
for(int i = 0; i < statresults.st_size; i++)
{
    fin.get(rBuffer[i]);
}

您可能希望使用无符号字符作为"字节"。你可以尝试这样的事情:

using byte = unsigned char;
...
byte* buffer = new byte[statresults.st_size];
fin.read( reinterpret_cast<char*>( buffer ), statresults.st_size );
...
delete[] buffer;