使用 fwrite/fread 对矩阵进行二进制(反)序列化不起作用

Binary (de-)serialization of a matrix using fwrite/fread doesn't work

本文关键字:二进制 不起作用 序列化 fwrite fread 使用      更新时间:2023-10-16

我正在尝试将双矩阵写入/读取为二进制数据,但在读取时没有得到正确的值。

我不确定这是否是使用矩阵的正确过程。


这是我用来编写它的代码:

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

这是我用来读取它的代码:

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

不起作用,因为myMatrix不是一个单一的连续内存区域,它是一个指针数组。你必须在循环中写入(和加载):

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" );
    for (int i = 0; i < rows; i++)
        fwrite (myMatrix[i] , sizeof(double) , colums , pFile );
    fclose (pFile);
}

阅读时类似。