有一行一大串的数据在一个bin文件中,没有任何符号隔开,每2字节为一个数值,我怎么把这写数全部取出来呢?我用的ifstream 的read 函数 但是一直输出同一个数值,想知道代码应该怎么写?最好能附上代码
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("xxx.bin");
int n[500];
size_t count = 0;
char buf[2] = {0};
unsigned int t;
while (!in.eof())
{
in.read(buf, 2);
t = buf[1];//存储时高位在后。
t <<= 8;
t |= buf[0];
n[count] = t;
count++;
}
in.close();
for (size_t i = 0; i < count; i++)
{
cout << n[i] << "\t";
if ((i + 1) % 8 == 0)
cout << endl;
}
cout << endl;
return 0;
}
获取字符数组,然后2个2个字符转换为数值。
char buffer[4]={0};
is.read(buffer,2);
int v = atoi(buffer);