fwrite()
will do the job of fseek(f,1,SEEK_CUR)
?
my code is :
while (fread(&tmp,sizeof(compt),1,fc))
{
if(tmp.num == m.crd ){
tmp.Solde-=m.mon;
fseek(fc,-sizeof(compt),SEEK_CUR);
fwrite(&tmp,sizeof(compt),1,fc);
}
if(tmp.num == m.deb){
tmp.Solde+=m.mon;
fseek(fc,-sizeof(compt),SEEK_CUR);
fwrite(&tmp,sizeof(compt),1,fc);
fseek(fc,1,SEEK_CUR);
}
}
My problem is that an infinity loop start.
when i turn on the debugger i see that the fread()
gave me the second struct again and again .
any help?
You must issue a call to fseek
or rewind
between read and write accesses to the same file. Fix the code this way:
while (fread(&tmp, sizeof(compt), 1, fc) == 1) {
if (tmp.num == m.crd ) {
tmp.Solde -= m.mon;
fseek(fc, -sizeof(compt), SEEK_CUR);
fwrite(&tmp, sizeof(compt), 1, fc);
fseek(fc, 0, SEEK_CUR);
}
if (tmp.num == m.deb) {
tmp.Solde += m.mon;
fseek(fc, -sizeof(compt), SEEK_CUR);
fwrite(&tmp, sizeof(compt), 1, fc);
fseek(fc, 0, SEEK_CUR);
}
}
Incidentally, from the context elements you provide, it does not make much sense to move the file pointer by just 1 byte with fseek(fc,1,SEEK_CUR);
, but it is necessary to call fseek(fc,0,SEEK_CUR);
to reset the file read/write state before switching back to read mode.