C 二进制文件 - 编写INT-奇怪的行为
C++ binary file - Writing ints - strange behaviour
我有一个简单的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 ()
调用过程中被解释为char
。3231748228
在十六进制为C0A09084
。std::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
值类型,您也可以确定代码仍然正确。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- 无法一次从二进制文件中读取一个 int
- 使用 c++ 时从二进制文件中读取 int 不正确
- C 二进制文件 - 编写INT-奇怪的行为
- 有没有一种优雅的方法来读取二进制文件并将其内容复制到向量<int>
- 将简短的int保存在二进制文件中而不是文本文件中
- 读取包含未签名INT的文件,然后将其写入C 中的二进制文件
- 将 int 的二进制文件读取到字符串 c++
- 将 int 写入二进制文件
- 如何在C++中将二进制文件上下文转换为 int/long 值
- "Right" C++ 中从大端二进制文件中检索 int 的方法
- 正在从二进制文件中读取双值和int值
- visual在C++中读取和写入int到二进制文件
- 我正在创建一个二进制文件,在其中插入一对int类型和一个结构,并看到下面给出的错误.请提出建议