The code here is being used for creating a Student Report card project. While trying to understand we can not figure out the use of and functions of the below code:
File.read(reinterpret_cast<char *> (&st), sizeof(student));
int pos=(-1)*static_cast<int>(sizeof(st));
File.read(reinterpret_cast<char *> (&st), sizeof(student));
if(st.retrollno()==n)
{
st.showdata();
cout<<"\n\nPlease Enter The New Details of student"<<endl;
st.getdata();
int pos=(-1)*static_cast<int>(sizeof(st));
File.seekp(pos,ios::cur);
File.write(reinterpret_cast<char *> (&st), sizeof(student));
cout<<"\n\n\t Record Updated";
found=true;
}
File.read(reinterpret_cast<char *> (&st), sizeof(student));
Reads thestudent
structure data directly from a file into the memory occupied byst
.The cast is because
read
expects achar*
, and this is how you convert a pointer of one type to a pointer of a completely unrelated type.Such code will only work when the file is written to and read from in binary mode, not to mention you pretty much have to create the file and read it on the exact same machine to be certain it will work as expected.
Even then, if the structure contains pointers, it's likely doomed to fail.
(-1)*static_cast<int>(sizeof(st));
turns the unsigned result of thesizeof
operator into a signed number, and multiplies it by-1
.The lines above feature what is called c++-style casts. The reason for using those, is that unlike a c-style cast, they will not preform a cast at any cost. They will only cast if the conditions for casting are met, which is much safer.
So casting unsigned to signed only requires a
static_cast
, which will fail if the compilers static type checking doesn't hold.reinterpret_cast
is a much more powerful beast (which is required when you want to somewhat ignore the type system), but still has some safeguards compared to a c-style cast.