I’m trying to read a binary file with the count of the elements at the first line of the binary file. The decimal version of the file is:
131072
32.75988
71.6028
113.0817173
.....
95.6124
My code to read the file is:
char TextName1[] = "BinaryArrayWithLength.bin";
FILE *InFile;
InFile = fopen( "BinaryArrayWithLength.bin", "rb" );
if(InFile == NULL)
{
printf( "Read Error\n" );
return 0;
}
else
{
fread( Length, sizeof(int), 1, InFile);
}
printf("%d\n", *Length);
The problem is I can get the right length which is 131072 if I compile it in Eclipse. If I compile my code in terminals with gcc, the number I got is 168430090.
I guess the problem is caused by different compilers. My gcc version is 4.2.1.The eclipse I used is Indigo for Mac. My Mac is OSX Lion.
Binary files are very platform-specific (as with binary data in general). Sometimes it’s also compiler-specific. Simply reading raw binary data to an integer is not going to be a cross-platform solution.
For starters, sizeof(int) is not something that’s going to be the same across all platforms. It might be 16-bits on one platform, 32-bit on another, and 64-bit on yet another. Just for an exercise, you should try printing out sizeof(int) in your program to see if it’s different between your local build and your remote gcc build.
The second issue you have to deal with is endianness. http://en.wikipedia.org/wiki/Endianness
There are libraries to help you with this, but reading all kinds of binary data in a cross-platform way is not exactly trivial.