首先,我将一些 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)
被正确读取,中间几乎没有零。
这是显示的样子:
First of all, you shouldn't use reinterpret_cast
here, because of the endianness - you lose portability. You write integers which are 4 bytes long in your case. Then you try to read the numbers to char which has only 1 byte. This explains why you see correct output for the first three numbers (they are in range from 0 to 255) and why there are some zeros between them.
Here, I found some piece of code on my hard drive, it probably could be written better, but it does the job and is a bit safer than your solution.
template<typename T> void ReadInteger(T &Output, const char* Buffer)
{
static_assert(std::numeric_limits<T>::is_integer, "return type cannot be non-arithmetic or floating point");
Output = 0;
for(unsigned int i = 0; i<sizeof(T); i++)
{
Output <<= 8;
Output |= Buffer[i];
}
}
template<typename T> void WriteInteger(T Value, char* Buffer)
{
static_assert(std::numeric_limits<T>::is_integer, "first parameter cannot be non-arithmetic or floating point");
for(unsigned int i = 0; i<sizeof(T); i++)
{
Buffer[sizeof(T)-i-1] = static_cast<char>(Value&0xff);
Value >>= 8;
}
}
Example usage:
int Value = 42;
char Buffer[sizeof(int)];
WriteInteger(Value, Buffer);
File.write(Buffer, sizeof(int));
// ...
File.read(Buffer, sizeof(int));
int a;
ReadInteger(a, Buffer);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句