如何用c++文件函数读写8位整数单位形式的数据

How to read and write data in 8 bit integers unit form by c++ file functions

本文关键字:单位 数据 整数 8位 c++ 何用 文件 函数 读写      更新时间:2023-10-16

是否可以以0到255的整数形式而不是8位字符存储数据?虽然两者是相同的事情,我们如何做到这一点,例如,用write()函数?是否可以直接将任何整数转换为char,反之亦然?像

这样的东西
{
    int a[1]=213; 
    write((char*)a,1);
} 

{
    int a[1]; 
    read((char*)a,1); 
    cout<<a;
}

工作从文件中的相同位置获得213 ?它可能在那台计算机上工作,但它是否可移植,换句话说,它是否适合跨平台项目?如果我使用这一原则为每个游戏关卡创建一个文件格式(将物体的坐标存储在当前关卡的文件中),它是否能够在其他计算机/系统/平台上运行以加载相同的关卡?

您显示的代码将写入a[0]的对象表示的第一个(最低地址)字节-它可能是也可能不是具有值213的字节。int的特定对象表示是实现定义的。

写入一个值为213的字节的可移植方法是

unsigned char c = a[0];
write(&c, 1);

您的想法是对的,但是还需要一些改进。

{
    int intToWrite = 213;
    unsigned char byteToWrite = 0;
    if ( intToWrite > 255 || intToWrite < 0 )
    {
        doError();
        return();
    }
    // since your range is 0-255, you really want the low order byte of the int.
    // Just reading the 1st byte may or may not work for your architecture. I
    // prefer to let the compiler handle the conversion via casting.
    byteToWrite = (unsigned char) intToWrite;
    write( &byteToWrite, sizeof(byteToWrite) );
    // you can hard code the size, but I try to be in the habit of using sizeof
    // since it is better when dealing with multibyte types
}
{
    int a = 0;
    unsigned char toRead = 0;
    // just like the write, the byte ordering of the int will depend on your
    // architecture. You could write code to explicitly handle this, but it's
    // easier to let the compiler figure it out via implicit conversions
    read( &toRead, sizeof(toRead) );
    a = toRead;
    cout<<a;
}

如果你需要最小化空间或者不能承受额外的字符,那么在你的整数中读/写一个特定的位置是绝对可能的。然而,它可能需要在新的头文件中进行链接(例如使用hton/ntons)或烦人(使用platform # definitions)。

它可以工作,但有一些注意事项:

  1. 使用reinterpret_cast<char*>(x)而不是(char*)x来明确执行通常不安全的强制转换。

  2. sizeof(int)因平台而异,因此您可能希望使用<cstdint>(如int32_t)的固定大小整数类型。

  3. 端序也可能因平台而异,因此在写入文件时应该注意平台字节顺序和交换字节顺序以保持一致的格式。您可以在运行时检测端序并手动交换字节,或者使用htonl和ntohl在主机和网络(大端)字节顺序之间进行转换。

另外,作为一个实际问题,我建议您选择基于文本的格式——它们不那么紧凑,但在出现问题时更容易调试,因为您可以在任何文本编辑器中检查它们。如果您认为加载和解析这些文件太慢,那么可以考虑改用二进制格式。