I am honestly really confused on reading binary files in C.
My data is in a format like:
- int header
- Cell[][] cells, 8×8 matrix
- Each cell is just a short id and a sbyte z.
However, something is clearly messing up and none of the values are accurate.
int i, j;
Block block;
// read 32 bits
fread( &(block.header), sizeof( int ), 1, mapFile );
// loop through to fill the 8x8 matrix
for( i = 0; i < 8; i++ )
{
for( j = 0; j < 8; j++ )
{
// read 16 bits
fread( &(block.cells[i][j].tileId), sizeof( short ), 1, mapFile );
// read 8 bits
fread( &(block.cells[i][j].z), sizeof( char ), 1, mapFile );
printf( "[%i][%i]: %x %i", i, j, block.cells[i][j].tileId, block.cells[i][j].z );
}
}
printf( "header: %i", block.header );
Output of above shows a bunch of lines with [n][n]: ffffa800 251.
My C# version works fine though:
Block block;
block.header = reader.ReadInt32();
block.cells = new Cell[8,8];
for( int i = 0; i < 8; i++ )
{
for ( int j = 0; j < 8; j++ )
{
block.cells[i, j].tileId = reader.ReadInt16();
block.cells[i, j].z = reader.ReadSByte();
}
}
reader.Close();
Output from that (correctly) shows [n][n]: a8 -5.
You should use more strictly defined types in C. For example, int32_t (stdint.h). It’s possible that your
shortis 32-bit (or even yourintis 16-bit), albeit unlikely.It’s probably also worthwhile to show us how the Block
structis defined.For reference:
SByte=int8_tInt16=int16_tInt32=int32_t