-3

The code here is being used for creating a Student Report card project but while trying to understand we can not figure out the use of and functions of the lines below from the code.

This:

File.read(reinterpret_cast<char *> (&st), sizeof(student));

and this:

int pos=(-1)*static_cast<int>(sizeof(st));

Here is the main code:

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;
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Possible duplicate of [In C++, why use static\_cast(x) instead of (int)x?](http://stackoverflow.com/questions/103512/in-c-why-use-static-castintx-instead-of-intx) – Arpit Solanki Dec 25 '16 at 10:28
  • 2
    Do you know about [`reinterpret_cast`](http://en.cppreference.com/w/cpp/language/reinterpret_cast) and [`static_cast`](http://en.cppreference.com/w/cpp/language/static_cast) and what they do? Do you know what arguments [`std::istream::read`](http://en.cppreference.com/w/cpp/io/basic_istream/read) accepts? Do you know what [`sizeof`](http://en.cppreference.com/w/cpp/language/sizeof) does? Then yu know all you need to know. – Some programmer dude Dec 25 '16 at 10:28
  • 3
    Possible duplicate of [What does reinterpret\_cast(&st) and (-1)\*static\_cast mean?](http://stackoverflow.com/questions/41319180/what-does-reinterpret-castchar-st-and-1static-castint-mean) – Danh Dec 25 '16 at 11:51
  • 2
    Are you two studying the same course in the same class? Those two question matchs exactly with each other? That two questions only differs by a typo!!! – Danh Dec 25 '16 at 11:52

1 Answers1

1
int pos=(-1)*static_cast<int>(sizeof(st));

converts the unsigned int type to integer and negates it, in order to compute the offset to seek backwards to in the next line

reinterpret_cast<char *> (&st)

just converts the pointer on the structure to a pointer on char so it's compatible with the function prototype. But the same pointer value is passed to the function.

So this code rewinds sizeof(st) bytes from the file and writes the new structure, updating the old one.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219