Reputation: 725
i need to read and write to the same file in sequential order (without seekg and seekp) but for some reason .write doesn't work !
here is my class
class student
{
int id ;
char name[20] ;
int m1 , m2 , m3 ;
public:
student()
{
}
student(int idd , char*n , int mm1 , int mm2 , int mm3 )
{
id = idd ;
strcpy(name , n);
m1 = mm1 ;
m2 = mm2 ;
m3 = mm3 ;
}
void show()
{
cout<<"student id : "<<id<<endl<<"student name : "<<name<<endl<<"mark 1 : "<<m1<<endl<<"mrak 2 : "<<m2<<endl<<"mark 3 : "<<m3<<endl ;
}
void get()
{
cout<<"enter student id : " ;
cin>>id ;
cout<<"enter student name : " ;
cin.ignore() ;
cin.get(name , 20) ;
cout<<"enter student's mark 1 :" ;
cin>>m1 ;
cout<<"enter student's mark 2 :" ;
cin>>m2 ;
cout<<"enter student's mark 3 :" ;
cin>>m3 ;
}
};
and here is my main function :
int main()
{
fstream file("f://records.dat" , ios::out | ios::in |ios::binary ) ;
if(!file)
{
cout<<"Error !";
int z ;
cin>>z ;
return 4 ;
}
modify(file);
int x ;
cin>>x ;
return 0 ;
}
and here is my function :
void modify(fstream &file)
{
int recnum ;
cout<<"enter the number of the record to be modified : " ;
cin>>recnum ;
file.seekg(0) ;
file.seekp(0);
student s1 ;
for(int i = 0 ; i<recnum-1 ; i++)
{
file.read((char *) &s1 , sizeof(s1)) ;
}
int x = file.tellp() ;
int y = file.tellg() ;
cout<<x<<endl<<y<<endl ;
student s2 ;
s2.get() ;
file.write((char *) &s2 , sizeof(student))
x = file.tellp() ;
y = file.tellg() ;
cout<<x<<endl<<y<<endl ;
file.flush() ;
file.seekg(0 , ios::beg);
if(file.eof())
{
cout<<"error !" ;
int x ;
cin>>x ;
}
while(file.read((char *) &s1 , sizeof(student)))
{
s1.show() ;
}
}
it seems that the write function int the method modify doesn't work so please could anybody help me ?????
Upvotes: 1
Views: 1029
Reputation: 725
i was compiling in visual studio 2010 , and when i took the same code and compiled it on other ides like code blocks , it works fine and outputs the expected results i think it is a .Net issue or something !
Upvotes: 0
Reputation: 96835
The problem is that bidirection file streams all hold a joint buffer where input and output both have an affect on the next character to be read and written. For instance, while reading is done, the output position indicator will also be incremented by the amount of characters read.
In your modify
function, you perform a write
directly after performing a read
without setting the output position indicator back to 0. This should always be done in order to receive expected results.
The same goes for output followed by input: Don't forget to set the seekg
position indicator as well.
Upvotes: 3