Hello all,
I recently did a programming test in which there was a ifstream section which I could not solve. Since then I have been trying to solve the problem in my free time to no avail.
The problem is basically to read from a binary file and extract the information there.
Here is the file format:
------------------------------------------------------------------------------ | File Offset (in Bytes)| Value Type | Value Description | ------------------------------------------------------------------------------ | 0 | Unsigned Integer (32 bits) | number of entities | ------------------------------------------------------------------------------ | 4 | Entity information (see | Entity 0 | | | below) | | ------------------------------------------------------------------------------ | 4+32 | Entity Information | Entity 1 | ------------------------------------------------------------------------------ | ... | ... | ... | ------------------------------------------------------------------------------ | 4 + (32 * N) | Entity Information | Entity N | ------------------------------------------------------------------------------ Entity Information: ------------------------------------------------------------------------------ | Offsett (in Bytes)| Value Type | Value Description | ------------------------------------------------------------------------------ | 0 | Unsigned short (16 bits) | Unique ID | ------------------------------------------------------------------------------ | 2 | Unsigned short (16 bits) | Entity type ID | ------------------------------------------------------------------------------ | 4 | Single-precision float (32 | Position X coordinate | | | bits) | | ------------------------------------------------------------------------------ | 8 | Single-precision float (32 | Position Y coordinate | | | bits) | | ------------------------------------------------------------------------------ | 12 | Single-precision float (32 | Forward Normal X | | | bits) | Component | ------------------------------------------------------------------------------ | 16 | Single-precision float (32 | Forward Normal Y | | | bits) | Component | ------------------------------------------------------------------------------
And here is my code:
void readFile()
{
ifstream ifs ( "binaryFile.bin" , ifstream::in );
while (ifs.good())
{
int numEntities = 0;
ifs.read( (char*)&(numEntities), sizeof(unsigned short));
for(int i=0; i<numEntities; i++)
{
unsigned short uID;
unsigned short eID;
float x;
float y;
float forward_x;
float forward_y;
ifs.read( (char*)&(uID), sizeof(unsigned short) );
ifs.read( (char*)&(eID), sizeof(unsigned short) );
ifs.read( (char*)&(x), sizeof(float) );
ifs.read( (char*)&(y), sizeof(float) );
ifs.read( (char*)&(forward_x), sizeof(float) );
ifs.read( (char*)&(forward_y), sizeof(float) );
}
}
ifs.close();
}
Thanks.