将向量<double>写入二进制文件并再次读取

Writing vector<double> to binary file and reading it again

本文关键字:二进制文件 读取 gt 向量 lt double      更新时间:2023-10-16

我正在尝试将双精度向量写入二进制文件。做完这些后,我想读它。这似乎行不通。这是代码:

ofstream bestand;
vector<double> v (32);
const char* pointer = reinterpret_cast<const char*>(&v[0]);
size_t bytes = v.size() * sizeof(v[0]);
bestand.open("test",ios::out | ios::binary);
for(int i = 0; i < 32; i++)
{
   v[i] = i;
   cout << i;
   }
bestand.write(pointer, v.size());
bestand.close();
ifstream inlezen;
vector<double> v2 (32);
inlezen.open("test", ios::in | ios::binary);
char byte[8];
bytes = v2.size() * sizeof(v2[0]);
inlezen.read(reinterpret_cast<char*>(&v2[0]), bytes);
for(int i =0; i < 32; i++){
 cout << endl << v2[i] << endl;
 }

这将输出"0 1 2 3 0 0 0......",因此它似乎可以正确读取前 4 个数字。

.write()采用字节数,而不是要写入的项目数:

bestand.write(pointer, v.size());

由于您已经计算了正确的值,因此请使用它:

bestand.write(pointer, bytes );