我最近做了一个编程测试,其中有一个我无法解决的ifstream部分。从那以后,我一直试图在空闲时间解决这个问题而无济于事。ifstream在编程测试中的帮助
问题基本上是从二进制文件中读取并提取信息。
下面是文件格式:
------------------------------------------------------------------------------ | 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 | ------------------------------------------------------------------------------
这里是我的代码:
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();
}
感谢。
为什么不让'numEntities'成为'unsigned short'? – meagar 2010-09-03 21:01:15