C++ 二进制文件 - 写入整数 - 奇怪的行为
C++ binary file - Writing ints - strange behaviour
我有一个简单的整数向量,我想将它写入一个二进制文件。例如:
#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
Hex 中的 84 与 Int 3231748228 不匹配。
这里发生了什么?
谢谢
问题是 std::vector<uint32_t>
中的每个值在 std::copy ()
调用期间都被解释为 char
。 3231748228
以十六进制表示为 C0A09084
。 std::copy ()
采用 uint32_t
值,将其截断为单字节,即 Little-endian processor. After writing byte 0x84
in file byte 0x0a
is added which corresponds to new line character.
上的 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
值类型,您也可以确保代码保持正确。
我有一个简单的整数向量,我想将它写入一个二进制文件。例如:
#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
Hex 中的 84 与 Int 3231748228 不匹配。
这里发生了什么?
谢谢
问题是 std::vector<uint32_t>
中的每个值在 std::copy ()
调用期间都被解释为 char
。 3231748228
以十六进制表示为 C0A09084
。 std::copy ()
采用 uint32_t
值,将其截断为单字节,即 Little-endian processor. After writing byte 0x84
in file byte 0x0a
is added which corresponds to new line character.
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
值类型,您也可以确保代码保持正确。