[英]Writing vector<double> to binary file and reading it again
I'm trying to write a vector of doubles to a binary file. 我正在尝试将双向量写入二进制文件。 After doing this I want to read it. 这样做后我想读它。 This doesn't seem to work. 这似乎不起作用。 Here is the code: 这是代码:
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;
}
This outputs "0 1 2 3 0 0 0......" so it seems it reads the first 4 numbers correctly. 这输出“0 1 2 3 0 0 0 ......”所以它似乎正确地读取前4个数字。
This .write()
takes the number of bytes , not the number of items to write: 这个.write()
接受的是字节数,而不是要写的项数:
bestand.write(pointer, v.size());
Since you've already computed the correct value, use it: 由于您已经计算了正确的值,请使用它:
bestand.write(pointer, bytes );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.