void updatebfile(char filename[MAX])
{
fstream writereadb;
char cont='y';
char filenameb [MAX];
int i=1;
int record;
student s;
strcpy(filenameb,filename);
strcat(filenameb,".dat");
writereadb.open(filenameb,ios::in | ios::out | ios::binary );
cout<<"------------------------------"
<<endl;
cout<<"Begin updating of binary file "
<<filenameb
<<endl
<<endl;
cout<<"Information for student file"
<<endl
<<endl;
while ( writereadb.read (reinterpret_cast <char *>(&s), sizeof (s) ) )
{
cout<<i
<<'\t'
<<s.identity
<<" "
<<s.name
<<endl;
i++;
}
do
{
cout<<endl
<<"Update record: ";
cin>>record;
cout<<endl
<<"Student id: ";
writereadb.seekg ((record - 1) * sizeof(s), ios::beg);//problem is here
writereadb.read (reinterpret_cast <char *>(&s), sizeof (s));//always reading last value
cout<<s.identity
<<endl;
cout<<"Update the name: ";
cin>>s.name;
writereadb.seekp((record-1)*sizeof(student),ios::beg);
writereadb.write (reinterpret_cast <const char *>(&s), sizeof (s));
cout<<"Any more update (y/n) :";
cin>>cont;
}while (cont=='y');
writereadb.close();
}
我有这个简单的功能,我想更新二进制文件。问题是我似乎无法设置get指针,我总是读取二进制文件中的最后一个值当我cout s.identity
答案 0 :(得分:2)
您总是尝试读取一个条目,只有成功才能使用结果(这是完全正确的)。如果没有成功,例如因为它遇到了EOF,所以streamstate将设置为“fail”。这会导致读取循环终止,但它也会导致该文件流上的任何后续操作失败,直到您明确重置streamstate。因此,您需要在该循环后调用writereadb.clear()
。
更多说明:
char filename[MAX]
不会将数组传递给函数!相反,它与char* filename
相同,即修改该参数将使其在调用函数中可见。使用std::string
,使用他们的c_str()
成员函数获取fstream
的指针。