本文介绍了写作矢量<&双GT;二进制文件并重新阅读它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想双打的载体写入到一个二进制文件。
这样做之后,我想读它。这似乎并没有工作。
这里是code:
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;
}
这个输出0 1 2 3 0 0 0 ......如此看来它正确读取第4个号码。
This outputs "0 1 2 3 0 0 0......" so it seems it reads the first 4 numbers correctly.
推荐答案
本 .WRITE()
需要数量的字节的,而不是数的项目的写:
This .write()
takes the number of bytes, not the number of items to write:
bestand.write(pointer, v.size());
既然你已经计算出正确的值,使用它:
Since you've already computed the correct value, use it:
bestand.write(pointer, bytes );
这篇关于写作矢量&lt;&双GT;二进制文件并重新阅读它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!