C 二进制文件 - 编写INT-奇怪的行为

C++ binary file - Writing ints - strange behaviour

本文关键字:INT- 二进制文件 编写      更新时间:2023-10-16

我有一个简单的int向量,我想将其写入二进制文件中。例如:

#include <fstream>
#include <vector>
int main () {
    std::vector<uint32_t> myVector{5, 10, 15, 20 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);
    std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(outfile));
    outfile.close(); 
    return 0;
}

然后,如果我在十六进制模式下检查文件" binary_ints.data",我有一个:

00000000: 050a 0f14 0a

那还可以!。

但是,如果MyVector具有此数据:

std::vector<uint32_t> myVector{3231748228};

然后,存储的十六进制很奇怪:

00000000: 840a

84在十六进制中与INT 3231748228不匹配。

这里发生了什么?谢谢。

问题是,您的std::vector<uint32_t>中的每个值在您的std::copy ()调用过程中被解释为char3231748228在十六进制为‭C0A09084std::copy ()采用uint32_t值,将其截断为单个字节,即小型处理器上的0x84。在添加了在文件字节0x0a中编写字节0x84之后,与新的行字符相对应。

一个可能的解决方案是使用ofstream::write()而不是std::copy ()

#include <fstream>
#include <vector>
int main () {
    std::vector<uint32_t> myVector{3231748228 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);
    outfile.write (
        (char*)(myVector.data ()), 
        myVector.size () * sizeof (decltype (myVector)::value_type));
    outfile.close();
    return 0;
}

请注意使用decltype ()。只需编写sizeof (uint32_t)就可以实现相同的效果,但是使用decltype (),即使您更改myVector值类型,您也可以确定代码仍然正确。