Andy
Andy

Reputation: 429

C++ writing and reading matrices of doubles from a binary file

Here comes a new issue after my previous question :

I've extended the code to perform matrix binary files I/O and when testing a simple write and read operation, I retrieved only the first line of the matrix...

I don't have managed to find my error, here is the new code :

double** bytes_to_matrix_block(std::ifstream& iF, int size1, int size2) {
    double** m = new double*[size1];
    double read;
    int i = 0, j = 0;

    if(!iF) {
        std::cout << "opening file for reading error";
        throw 1;
    }
    while(i < size1 && !iF.eof()) {
        m[i] = new double[size2];
        while(j < size2 && !iF.eof()) {
            iF.read( reinterpret_cast<char*>( &read ), sizeof read );
            m[i][j] = read;
            std::cout << read << ", ";
            j++;
        }
        std::cout << std::endl;
        i++;
    }
    if(i < size1 || j < size2) {
        std::cout << "premature end of file while reading..." << std::endl;
        throw 1;
    }
    return m;
}

void matrix_block_to_bytes(double** m, int size1, int size2, std::ofstream& oF){

    if(!oF){
        std::cout << "opening file for writing error";
        throw 1;
    }

    double cdbl;

    for(int i = 0; i < size1; i++){
        for(int j = 0; j < size2; j++){
            cdbl = m[i][j];
            std::cout << cdbl << ", ";
            oF.write( reinterpret_cast<char*>( &cdbl ), sizeof cdbl );
        }
        std::cout << std::endl;
    }
}

Thanks by advance

Upvotes: 4

Views: 3436

Answers (1)

b.buchhold
b.buchhold

Reputation: 3896

When reading, you forget to reset j to 0 for new lines

while(i < size1 && !iF.eof()) {
// Missing:
j = 0;

Upvotes: 2

Related Questions