Original Post
Is there standard way of using the stream operators <<,>> with binary files?
Lets say we have two structs like this:
struct Header
{
int Magic;
int NumElements;
}
struct Element
{
int Data;
char Data2[128];
}
and a binary file which holds the header and then n Elements objects.
We first read the header and then the elements. Would it make sense to define a istream operators >> like this:
std::istream& operator>>(std::istream& is, Header& header)
{
return is.read( reinterpret_cast(&header), sizeof(Header) );
}
And the same for the Element struct. The we could do something like this:
std::vector g_Data;
void ImportData(const std::string& filename)
{
// I don''t use any error checking here for clarity...
std::ifstream is(filename, std::ios::in|std::ios::binary);
Header header;
is >> header;
g_Data.resize(header.NumElements);
Element e;
for (int i = 0; i < header.NumElements; ++i)
{
is >> e;
g_Data = e;
}
}
What I wonder if the use of the reinterpret_cast is correct and good style? What do you think of this implementation? Is there a better/standard way of parsing files with the above structure using the stream classes? What about speed issues? As in my previous post "memcpy vs. std::copy" are there any differences between the C-Functions (fread,...) and the Standard Library counterparts, especially regarding speed issues?
Any examples or references that you could recommend?
Help / critic / comments are greatly appreciated :-)
-Dirk