c++ - 将 vector<double> 写入二进制文件并再次读取

标签 c++ file vector binary

我正在尝试将 double vector 写入二进制文件。 完成此操作后,我想阅读它。这似乎不起作用。 这是代码:

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 );

关于c++ - 将 vector<double> 写入二进制文件并再次读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365097/

相关文章:

c++ - STL容器插入元素和内存透视图

c# - 为什么当我使用带有字符串返回类型的 OCX 方法时 C# 程序关闭?

C,将文件指针作为参数传递给函数

c++ - 在具有结构的 vector 中获取项目位置

c++ - 我可以使用占位符作为 C++ 中数组的索引吗?

c++ - 为 Clang 静态分析器编写自定义检查器

c++ - 有没有办法调用被重写的对象的基类方法? (C++)

c - gets 和 fopen 不起作用,甚至更改为 gets_s 和 fopen_s

file - 在 Go 中使用相同的 *os.File 写入和读取文件

c++ - 节点插入cpp