Just because I've never read binary files before I wrote a program that reads binary STL files. I use ifstream
s read member that takes a char* a parameter. To cast my struct to a char* I use a reinterpret_cast. But as far as I remember every book about C++ I read said something like "don't use reinterpret_cast except you have to". What would be a better way read binary data, not necessarily direct, but at last into a struct and without reinterpret_cast?
The main function:
std::ifstream in (cmdline[1].c_str(), std::ios::binary);
in.seekg(80, std::ifstream::beg); //skip header
int numTriangle;
in.read (reinterpret_cast<char*>(&numTriangle), sizeof(int)); //determine number of triangles
//create triangle data type and read data
triangle* t = new triangle();
for (int i = 0; i < numTriangle; ++i) {
in.read(reinterpret_cast<char*>(t), triangle::size);
std::cout << *t; // there's an opertor<< for triangle
}
delete t;
in.close(); //close file read from
And the triangle struct
//attempt to get the right size of a class without structure padding
#pragma pack(push)
#pragma pack(1)
//standard STL triangle data structure
struct triangle {
public:
float n[3]; //normals, 4*3=12 bytes
float x[3]; //first point of the triangle, 4*3=12 bytes
float y[3]; //second point of the triangle, 4*3=12 bytes
float z[3]; //third point of the triangle, 4*3=12 bytes
long int a; //attributes, 2 bytes
static const int size = 12+12+12+12+2; //sum of member variables
//static const int size = sizeof(n) + sizeof(x) + sizeof(y) + sizeof(z) + sizeof(a);
};
#pragma pack(pop)
(Extra question: #pragma pack(1) doesn't work with cygwins g++-4. How can I determine the size of the struct?)