Write to binary file

Friends.
I am with the program segment below, and the following is happening.
If I take a while ( in bold ) to see if the code exists, the program writes records normally. If I leave this while, the program runs without error but does not record the record data in the file.
I can not figure out. I've tried everything. It has to do something with positioning end of file.
I need help on it.
Thanks.

void novo_registro(fstream &f)

{
int mcodigo,achei=0;
cliente c;
cout << "Digite codigo: ";
cin >> mcodigo;
// verifica se já existe o codigo

f.seekg (0, ios::beg);
while (! f.eof())
{
f.read((char *)(&c),sizeof(cliente));
if (c.codigo == mcodigo)
{
achei= 1;
break;
}
}


if (achei==0)
{
c.codigo = mcodigo;
fflush(stdin);
cout << "Entre nome: ";
gets(c.nome);
fflush(stdin);
cout << "Entre telefone: ";
gets(c.tel);
fflush(stdin);
cout << "Entre email: ";
gets(c.email);
c.situacao=1;
f.seekp(0,ios::end);
f.write((const char *)(&c),sizeof(cliente));
f.flush();
cerr <<"\n Registro gravado com sucesso.\n";
}
else
cerr << "Codigo #" << mcodigo << " existente." << endl;
system("pause");
}
Last edited on
It's hard to say without knowing what is the code for and when it is written in another language, but anyway, try replacing your while loop with
1
2
3
4
5
6
while( file.read( (char *)(&c), sizeof(cliente) ) ){
   if (c.codigo == mcodigo){
      achei= 1;
      break;
   }
}
Topic archived. No new replies allowed.