how the read statement knows what part of the binary file to each member |
It doesn't.
What you need to understand is that a class is merely a bunch of variables bound together. In memory, your class might actually look like this*:
[country (20 bytes)] [population[0] (4 bytes)] [population[1] (4 bytes)] ... [population[5] (4 bytes)]
*...Or not. It depends on the compiler and the platform.
When you pass a pointer to an Emp casted as a pointer to char to read(), you're saying "read the contents of the file into here as though it was an array of chars, regardless of what actually was there".
Like I said before, this is a bad idea. This logic depends on the data having the same shape in the file as it would have in memory.
Suppose instead of the above scheme, the compiler decided for whatever reason to put 1 padding byte after country:
[country (20 bytes)] [padding (1 byte)] [population[0] (4 bytes)] [population[1] (4 bytes)] ... [population[5] (4 bytes)]
The code no longer works, because now read() is writing one of the bytes to a location that cannot be accessed as a member (without overflowing country).
An even more common occurrence is the file having a different endianness (
http://en.wikipedia.org/wiki/Endianness) than the platform, which also results in corrupt data.