Understanding the problem after C ++ code. (Seekp)

#include<stdio.h> #include<fstream.h> class Test { char name[10]; int data; public: void getData() { cin>>name; cin>>data; } void display() { cout<<name<<data; } void modify() { cin>>name; cin>>data; } }; int main() { Test t1,t2,t3,t4; // remove("FileIO.dat"); t1.getData(); t2.getData(); t3.getData(); t4.getData(); fstream fp1("FileIO.dat",ios::out|ios::app); fp1.write((char*)&t1,sizeof(t1)); fp1.write((char*)&t2,sizeof(t2)); fp1.write((char*)&t3,sizeof(t3)); fp1.write((char*)&t4,sizeof(t4)); fp1.close(); fstream fp2("FileIO.dat",ios::in|ios::out); fp2.read((char*)&t1,sizeof(t1)); fp2.read((char*)&t2,sizeof(t2)); int pos=-1*sizeof(t2); // ****** not understanding this line cout<<pos; fp2.seekp(pos,ios::cur); t2.modify(); fp2.write((char*)&t2,sizeof(t2)); fp2.read((char*)&t3,sizeof(t3)); fp2.read((char*)&t4,sizeof(t4)); t1.display(); t2.display(); t3.display(); t4.display(); fp2.close(); return 0; } 

The program is written in C ++ turbo and is engaged in writing objects to files and reading them, as well as updating the object that was written to the file.

In the above code, I don't understand why -1 is multiplied by the sizeof of the object to get the position. Someone please explain.

+4
source share
1 answer

Because your program reads data from t1, reading data from t2, changing t2, and then writing the contents of t2.

When fp2 is opened first, the file looks like this ( ^ represents the current position of the file pointer):

 +-----------+-----------+-----------+-----------+ | t1 data | t2 data | t3 data | t4 data | +-----------+-----------+-----------+-----------+ ^ | 

After reading t1 and t2, the pointer will now point to the beginning of t3:

 +-----------+-----------+-----------+-----------+ | t1 data | t2 data | t3 data | t4 data | +-----------+-----------+-----------+-----------+ ^ | 

Now, to write t2 data, we need to move the file pointer back to the beginning of t2. How far is it? -1 * sizeof(t2) :

 +-----------+-----------+-----------+-----------+ | t1 data | t2 data | t3 data | t4 data | +-----------+-----------+-----------+-----------+ ^ | <-----------+ | This distance == sizeof(t2) 

From there, your program runs fp2.seekp(pos,ios::cur); . Since pos is negative, it moves the file pointer back, and your file remains in this state:

 +-----------+-----------+-----------+-----------+ | t1 data | t2 data | t3 data | t4 data | +-----------+-----------+-----------+-----------+ ^ | 

And now you can overwrite t2 data.

+7
source

All Articles