xxvms wrote: |
---|
thanks, so does this work like in a loop with steps?
First time it reads file it goes the size of person object (which is 82 bytes)
then goes to the next person? |
The loop reads a number of bytes equal to the value of “sizeof(person)” at every iteration, starting from the byte in file following the last reading operation.
I can’t know what you supposed it should do, but I suspect you assume your code perform operation it doesn’t do.
Have you tested it? Assuming you have got a group.dat file like this:
Danielle Brown 20
Lindsey Carmichael 21
Miroslava Cerna 22
Mel Clarke 23
Gizem Girismen 24
Fu Hongzhi 25
Gao Fangxia 26
Kim Ki Hee 27
Kim Ran Sook 28
Lenka Kuncova 29
Malgorzata Olejnik 30
Lee Hwa Sook 31
Marketa Sidkova 32
Xiao Yanhong 33 |
your output will be:
There are 3 persons in file
Name: Danielle Brown 20
Lindsey Carmichael 21
Miroslava Cerna 22
Mel Clarke 23
Gizem Age: 28005
Name: Girismen 24
Fu Hongzhi 25
Gao Fangxia 26
Kim Ki Hee 27
Kim Ran Sook 28
Lenka Age: 24939
Name: Kuncova 29
Malgorzata Olejnik 30
Lee Hwa Sook 31
Marketa Sidkova 32
Xiao Yanh Age: 26734 |
As you can see, data are wrong, but the problem is not your reading procedure.
std::basic_istream::read(char_type* s, std::streamsize count)
stores “count” characters inside “s”.
Passing the reference to a class instead of a “char*” and then trying to “reinterpret_cast” it means playing a dirty trick which doesn’t happen to work.
I may agree that a pointer to a class in all likelihood is a pointer to the memory area where its properties are stored, but you can’t take it for granted, not even if there aren’t static variables.
Your code could have a chance to work if every line of the file were long exactly 80*sizeof(char) + sizeof(person).
This because in some machine it could be that your
char name[80];
and
short age;
were stored in adjacent memory cells. But I think there’s a subtle difference between gambling and programming.
BTW, you should consider that you don’t know which is the size of 80*sizeof(char) + sizeof(person) because the size of “short int” is not guarantee to be 16 bits, but *at least* 16 bits:
http://en.cppreference.com/w/cpp/language/types
It means it’s machine-dependent.