gpt4 book ai didi

c++ - 用C++读取/写入二进制文件

转载 作者:行者123 更新时间:2023-12-02 09:59:31 24 4
gpt4 key购买 nike

我有一个要存储在外部存储器中的值矩阵。
我正在将矩阵写入文件,然后使用读/写命令一次一行地编辑文件。最初,我使用getLine()方法从文件中读取矩阵,这在时间方面效率太低。
现在,我正在尝试使用fstream类的读/写命令写入二进制文件。我的程序在到达该行时终止:

IOfile.read(reinterpret_cast<char*>(&d1), (n - i) * sizeof(double)); //gets all elements in the row after element i
为什么不将文件中的值读入 vector 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));
vector 的地址与您要写入的基础数组不同。这也适用于d2等。

关于c++ - 用C++读取/写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63342970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com