I’m trying to write/read a double matrix to file as binary data but I’m not getting the correct values when reading.
I’m not sure if this is the correct procedure to do it with matrices.
Here’s the code that I’m using to write it:
void writeMatrixToFileBin(double **myMatrix, int rows, int colums){
cout << "\nWritting matrix A to file as bin..\n";
FILE * pFile;
pFile = fopen ( matrixOutputName.c_str() , "wb" );
fwrite (myMatrix , sizeof(double) , colums*rows , pFile );
fclose (pFile);
}
Here’s the code that I’m using to read it:
double** loadMatrixBin(){
double **A; //Our matrix
cout << "\nLoading matrix A from file as bin..\n";
//Initialize matrix array (too big to put on stack)
A = new double*[nRows];
for(int i=0; i<nRows; i++){
A[i] = new double[nColumns];
}
FILE * pFile;
pFile = fopen ( matrixFile.c_str() , "rb" );
if (pFile==NULL){
cout << "Error opening file for read matrix (BIN)";
}
// copy the file into the buffer:
fread (A,sizeof(double),nRows*nColumns,pFile);
// terminate
fclose (pFile);
return A;
}
It doesn’t work because
myMatrixis not a single continuous memory area, it’s an array of pointers. You have to write (and load) in a loop:Similar when reading.