Search code examples
c++multidimensional-arraybinaryfilesbinary-data

Writing/Reading 2D array to Binary File C++


I am trying to write data from a 2D array into a binary file. I am only writing the data that has a value greater than 0. Therefore, if the data is is 0, it will not be written to the file. The data is as follows:

Level       0   1   2   3   4   5

Row 0       4   3   1   0   2   4
Row 1       0   2   4   5   0   0 
Row 2       3   2   1   5   2   0
Row 3       1   3   0   1   2   0

void { 

    // This is what i have for writing to file.

    ofstream outBinFile; 
    ifstream inBinFile; 
    int row; 
    int column; 

    outBinFile.open("BINFILE.BIN", ios::out | ios::binary);

    for (row = 0; row < MAX_ROW; row++){

        for (column = 0; column < MAX_LEVEL; column++){

          if (Array[row][column] != 0){

             outBinFile.write (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
          }
        }
    } 

    outBinFile.close(); 

    // Reading to file. 

    inBinFile.open("BINFILE.BIN", ios::in | ios::binary);

    for (row = 0; row < MAX_ROW; row++){

        for (column = 0; column < MAX_LEVEL; column++){

          if (Array[row][column] != 0){

             inBinFile.read (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
          }
        }
    } 

    inBinFile.close();  
}

All the data being read is being inserted into the first row, how can i get the data to load as i exited the program?


Solution

  • You are reading only when data is not equal zero, means that it gets locked with first zero. Once it reaches zero it stops reading.

    Before "if command" read file to some other varaible then in if (variable != 0) Array[row][column] = variable.

    If your Array is initialized with data, maybe take a look into setting position of your reading. So to set ok I have zero, I should read from another position next.