将未签名的数据写入 C++ 中的二进制文件

writing unsigned data to binary file in C++

本文关键字:C++ 二进制文件 数据      更新时间:2023-10-16

我正在尝试编写序列

56 4F 4C 03

作为二进制(无符号字符)放入文件中。

在 ASCII 中,这应该拼写出"VOL",根据我的十六进制编辑器,对应于字节"03"的第 4 个字符是非显示字符。

下面正确写入"VOL",但我不知道如何编写原始无符号的"03"数据,因为它是一个不显示的字符。我该怎么做?我应该使用像0x03这样的标识符进行编码,还是有更清洁的方法?

int main()
{
    std::ofstream outfile;
    outfile.open ("data.vol", std::ios::out | std::ios::binary | std::ios::app);
    std::string str = "VOL";
    std::string::size_type sz = str.size();
    // when i leave this line out, it writes to string?
    outfile.write(reinterpret_cast<char*>(&sz), sizeof(std::string::size_type));
    outfile.write(str.data(),sz);
    std::string m_version_identifier = "3";
    outfile.write((char*)&m_version_identifier.data()[0],m_version_identifier.size());
    outfile.close();
    std::cout << "done" << std::endl;
    return 0;
}

您正在寻找字符'3'或字符串"VOL3"

写入字节本身可能是更干净的方法:

int version = 3;
outfile.write(&version,1);