【发布时间】:2018-06-10 14:28:00
【问题描述】:
首先我将一些 int 变量写入 .bin 文件。然后我尝试读回这些数字,但我没有这样做。
我是这样写的:
std::ofstream OutFile;
OutFile.open("encode.bin", std::ios::out | std::ios::binary);
for(int i = 0; i < all.size(); i++){
int code = codes[i];
OutFile.write(reinterpret_cast<const char *>(&code), sizeof(int));
}
OutFile.close();
这就是我写数字时 .bin 文件的样子:65, 66, 66, 257, 258, 260
Offset: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000: 41 00 00 00 42 00 00 00 42 00 00 00 01 01 00 00
00000010: 02 01 00 00 04 01 00 00
字节序有问题吗?我看到数字是相反的。
以及我的阅读方式:
std::vector<int> allCodes;
std::ifstream inputD(file, std::ios::binary);
std::vector<char> buffer((
std::istreambuf_iterator<char>(inputD)),
(std::istreambuf_iterator<char>()));
for (auto a : buffer) {
data.push_back(static_cast<int>(a));
allCodes.push_back(a);
};
当我显示我的向量时,前三个数字(65, 66, 66) 被正确读取,中间有几个零。
这是显示的样子:
【问题讨论】: