c++ - 在 C++ 中读取/写入二进制文件
问题描述
我有一个很大的值矩阵,我试图将它们存储在外部存储器中。
我正在将矩阵写入文件,然后一次使用读/写命令编辑文件一行。最初,我使用 getLine() 方法从文件中读取矩阵,这在时间方面效率太低了。
现在,我正在尝试使用 fstream 类读/写命令写入二进制文件。我的程序在到达该行时终止:
IOfile.read(reinterpret_cast<char*>(&d1), (n - i) * sizeof(double)); //gets all elements in the row after element i
为什么它不将文件中的值读入向量 d1?
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<double> vector_solve(vector <double>& B) {
vector <double> MI(B.size());
int n = B.size();
/* Writing a matrix of values to the file */
fstream IOfile;
IOfile.open("test_matrix.bin", ios::in | ios::out | ios::binary);
if (!IOfile.is_open())
cout << "Error opening file: test_matrix.bin" << endl;
else {
for (int i = 0; i < n; i++) //rows
for (int j = 0; j <= n; j++) //columns
if (j == n) //write final column as original vector
IOfile.write(reinterpret_cast<char*>(&B[i]), sizeof(double));
else {
double d1 = 500; //TO-DO: double d1 = (*Mfunc)(i, j, dtMU);
IOfile.write(reinterpret_cast<char*>(&d1), sizeof(double));
}
//loop to perform the gauss elimination
for (int i = 0; i < (n - 1); i++) {
for (int k = (i + 1); k < n; k++) {
vector <double> d1(n + 1); //row1
vector <double> d2(n + 1); //row2
int SG1 = i * sizeof(double); //file get pointer
cout << "SG1 is: " << SG1 << endl;
IOfile.seekg(SG1); //Sets the get position to element i
cout << "ABOUT TO READ" << endl;
IOfile.read(reinterpret_cast<char*>(&d1), (n - i) * sizeof(double)); //gets all elements in the row after element i
cout << "d1[0] is equal to: " << d1[0] << endl;
cout << "d1[1] is equal to: " << d1[1] << endl;
cout << "d1[2] is equal to: " << d1[2] << endl;
cout << "d1[3] is equal to: " << d1[3] << endl;
int SG2 = k * sizeof(double);
IOfile.seekg(SG2); //Sets the get position to element k
IOfile.read(reinterpret_cast<char*>(&d2), (n - k) * sizeof(double)); //gets all elements in the row after element k
double t = d2[i] / d1[i];
for (int j = 0; j <= n; j++) {
double temp1 = d1[j];
d2[j] = d2[j] - t * temp1;
}
IOfile.seekp(SG2);
IOfile.write(reinterpret_cast<char*>(&d2), sizeof(d2));
}
for (int i = (n - 1); i >= 0; i--) {
vector <double> d1(n + 1);
int SG1 = i * sizeof(double);
IOfile.seekg(SG1);
IOfile.read(reinterpret_cast<char*>(&d1), (n - i) * sizeof(double));
MI[i] = d1[n];
for (int j = (i + 1); j < n; j++)
if (j != i)
MI[i] = MI[i] - d1[j] * MI[j];
MI[i] = MI[i] / d1[i];
}
IOfile.close();
}
}
return MI;
}
为什么它能够以二进制形式写入文件但不能从中读取?任何帮助表示赞赏,谢谢。
解决方案
尝试
IOfile.read(reinterpret_cast<char*>(d1.data()), (n - i) * sizeof(double));
向量的地址与您尝试写入的底层数组不同。这也适用于 d2 等。
推荐阅读
- css - 如何将 HeaderRenderer 添加到 react-data-grid?
- c# - 尽管缺少道具,但使用 MessagePackSerializer 解包
- android - 如何使用谷歌地图等自动建议实现地址搜索?
- python - 如何选择性地从 AWS S3 读取 Parquet 文件作为 Dask 数据框?
- c++ - 别名漏洞是否适用于签名字符?
- php - 警告:取消链接($name):权限被拒绝
- ios - 如何抽象网络模型获取
- reactjs - 从公共默认导入静态文件
- node.js - 希望 Jenkins 管道脚本使用测试数据库创建 docker 容器,对其进行测试,销毁容器
- pandas - 如何将增量数字添加到熊猫中的特定列