Question

I'm using C++ to write an int array to a binary file like so:

int * _row;
_row = new int[200];
// .. fill array

// outputs 8, so one integer should be 8 bytes long
cout << sizeof _row << endl;

ofstream fHandle;
fHandle.open("~/row.bin", ios::out | ios::trunc | ios::binary);
for (int ii=0;ii<200;ii++) {
  fHandle.write( (char*)&_row[ii], sizeof _row );
}
fHandle.close();

Now when I read it in MATLAB (as below), I don't get the original array.

fid = fopen("~/row.bin");
x = fread(fid, 'int32');
fclose(fid)

I realise I should use a data type consisting of 8 bits (such as 'int64'), but with 'int32' I at least get the right values. However, each value is read twice! I don't have any explanation for this. I end up with an array of size 400 (which makes sense since I'm reading smaller chunks). If I choose 'int64', I end with the right dimension, but the values are wrong.

Do you have any explanation for this?

Was it helpful?

Solution

fHandle.write( (char*)&_row[ii], sizeof _row );

This should be:

fHandle.write( (char*)&_row[ii], sizeof(int));

Since you want to write one integer inside each iteration of your for loop right? Since sizeof is evaluated at compile time sizeof row only returns the size of a pointer (int*) which is 8 bytes on a 64-bit system (and 64-bit compile). sizeof row would only return the (byte-)size of the array if row would be a static array (in the form int row[200];). Since all of this is a bit tricky to explain, I wrote a small example on codepad: http://codepad.org/FdPfo62y , it uses 32-bit so the pointers are just 4 bytes in size. I used int16_t (which is 2 bytes in size) to show the discrepancy between the pointer and data type size.

You could also do the whole write without the for loop:

fHandle.open("~/row.bin", ios::out | ios::trunc | ios::binary);
fHandle.write((char*)_row, sizeof(int)*200);
fHandle.close();

Also, if you use explicit data type sizes in Matlab I would suggest you use them in C++ too, so with C++11 you could use int32_t instead of int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top