2012-09-25 30 views
1

我想寫矩陣的序列化/讀取的雙矩陣文件作爲二進制數據,但我沒有得到的時候正確的價值觀讀。二進制(去)使用FWRITE/FREAD不起作用

我不確定這是否是正確的程序與矩陣做。


下面是我用來寫代碼:

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

您是否考慮過爲您的矩陣和[boost :: serialization]使用'std :: vector >'(http://www.boost.org/doc/libs/1_51_0/libs/serialization /doc/index.html)爲您的二進制序列化?請注意,以便攜方式二進制存儲浮點數不是微不足道的。 – moooeeeep

+0

你好,現在我沒有考慮使用矢量庫或提升。但這可能是未來的一個選擇。謝謝。 – RandomGuy

回答

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

讀取時類似。

+0

嗨!謝謝回答。看起來你的代碼工作正常。但有一個小問題:'myMatrix [i]'應該是'myMatrix [i]',否則它將指向指針位置而不是_i_行。 – RandomGuy

+0

@RandomGuy是的,你說得對。從我的答案中刪除了&。 –