【问题标题】:Binary (de-)serialization of a matrix using fwrite/fread doesn't work使用 fwrite/fread 对矩阵进行二进制(反)序列化不起作用
【发布时间】:2012-09-25 10:12:24
【问题描述】:

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

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


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

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

【问题讨论】:

  • 您是否考虑过将std::vector&lt;std::vector&lt;double&gt; &gt; 用于您的矩阵并使用boost::serialization 用于您的二进制序列化?请注意,以可移植方式二进制存储浮点数并非易事。
  • 你好,现在我没有考虑使用向量库或 boost。但这可能是未来的一种选择。谢谢。

标签: c++ serialization file-io matrix binary-data


【解决方案1】:

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

阅读时类似。

【讨论】:

  • 嗨!谢谢回答。似乎您的代码工作正常。但是有个小问题:&amp;myMatrix[i] 应该是myMatrix[i] 否则会指向指针位置而不是 i 行。
  • @RandomGuy 是的,你是对的。从我的回答中删除了&amp;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2015-06-17
  • 2012-02-29
  • 2014-01-04
相关资源
最近更新 更多