1

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

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


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

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

1 回答 1

2

它不起作用,因为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);
}

阅读时类似。

于 2012-09-25T10:21:07.617 回答