>我需要按顺序读取和写入同一个文件(没有seekg和seekp)但是由于某种原因,.write不起作用!
这是我的班级
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 ;
}
};
这是我的主要功能:
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 ;
}
这是我的函数:
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() ;
}
}
似乎方法修改的写入函数不起作用,所以请有人帮我?????
问题是双向文件流都包含一个联合缓冲区,其中输入和输出都会影响要读取和写入的下一个字符。例如,在读取完成时,输出位置指示器也将随着读取的字符量而增加。
在modify
函数中,您可以在执行read
后直接执行write
,而无需将输出位置指示器设置回 0。为了获得预期的结果,应始终这样做。
输出后跟输入也是如此:不要忘记设置seekg
位置指示器。
我在 Visual Studio 2010 中编译,当我使用相同的代码并在代码块等其他 IDE 上编译它时,它工作正常并输出预期的结果我认为这是一个 .Net 问题或其他什么!