我最近做了一個編程測試,其中有一個我無法解決的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