Link to home
Start Free TrialLog in
Avatar of keepthursdayspecial
keepthursdayspecial

asked on

Reading and Writing Boost multi_array's to binary files

I am having problems writing a boost multi_array to a binary file and then reading it back.

I have a 3d multi_array which contains integers:

typedef boost::multi_array<int, 3> i3dArray;
typedef i3dArray::index iIndex;

Start Program
{
   i3dArray contactMatrix(boost::extents[NOATOMS][NOATOMS][NO_DISTANCES_BINS]);  // [167][167][150]

   loop through files of atomic structures
   {
        count the number of atom types i see at different distances and increment the relevant array positions
         i3dArray[i][j][k]++
    }

      // Verify values - this works (i.e. the i3dArray has correct values)
     for(iIndex i = 0; i != 50; ++i)
        for(iIndex j = 0; j != 50; ++j)
           for(iIndex k = 0; k != 50; ++k)
              cout << contact[i][j][k];

     // Then i want to write this object to a binary file.
    ofstream outfile( outname.c_str(), ios::out | ios::binary);
      outfile.write( (char*)&contact, sizeof(contact) );
    outfile.close();    

    // later i want to read in this object
    ifstream Source(file, ios::in | ios::binary );
    if (Source.fail())
      exit(1);
    Source.read( (char*)&contact, sizeof(contact) );
    Source.close();

      // Printing gives me a Segmentation Fault
     for(iIndex i = 0; i != 50; ++i)
        for(iIndex j = 0; j != 50; ++j)
           for(iIndex k = 0; k != 50; ++k)
              cout << contact[i][j][k];
}

I know this is a crude and incompetent method of writing an object but more correct ideas would be appreciated.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of keepthursdayspecial
keepthursdayspecial

ASKER

Oh, I see.

However, this doesn't write anything to the binary file.
     string outname = "out/pdb"+pdbfiles[t]+".ent.chem";
      ofstream outfile( outname.c_str(), ios::out | ios::binary );
      outfile.write( (char*)contactMat.data(), sizeof(int)*contactMat.size() );
      outfile.close();

when i check the sizeof(int)*matrix i get 72 which is the same size as the output file.  

      cout << sizeof(int) << " " << sizeof(int) * contactMat.size() << " " << contactMat.size() << endl;

So 4 72 8.

The multi_array is [18] [18] [150] is this instance.

When I read the file back into a new multi_array of the same size i get an array of 0's.