Modify a binary file in C

0

I need to read and modify a binary file, I am using this code:

FILE *fp; t_data dat; fp=fopen("file.bin","r+b"); 
fread(&dat,sizeof(t_data),1,fp); 
while(!feof(fp))
{
    if(dat.aaaa==2018)
    {
        int pos = ftell(fp)-sizeof(t_data);
        dat.prec=2;
        fseek(fp,pos,SEEK_SET);
        fwrite(&dat,sizeof(t_data),1,fp);
    }
    fread(&dat, sizeof(t_data),1,fp);
}
fclose(fp);

the program enters a loop apart from not modifying the data with which I want to work, I do not understand what I'm doing wrong, what can it be? thanks

    
asked by Sebastardo 11.10.2018 в 16:12
source

1 answer

0

ok, I found the reason why the loop was made

FILE *fp; t_data dat; fp=fopen("file.bin","r+b"); 
fread(&dat,sizeof(t_data),1,fp); 
while(!feof(fp))
{
    if(dat.aaaa==2018)
    {
        int pos = ftell(fp)-sizeof(t_data);
        dat.prec=2;
        fseek(fp,pos,SEEK_SET);
        fwrite(&dat,sizeof(t_data),1,fp); // faltaba esta linea
    }
    fread(&dat, sizeof(t_data),1,fp);
}
fclose(fp);

you must call fseek or rewind between writing and reading to reset the read / write state before switching back to reading mode

    
answered by 11.10.2018 в 17:05