Fread () doesn't work after fseek () with fwrite () in C

In my program, I am making a binary file containing structs (each struct contains one integer) ... and I put 3 structs in a file ... I want to create a file first ... then close it ... then repeat it like "rb + "mode ... and I want to read structures from a file and change its value (member data) and overwrite it in the same file as this way:

#include <stdio.h>
main()
     {
         int i;

         struct
         {
             int data;
         }x;  

         FILE* myfile=fopen("d:\\text.bin","wb");

         for(i=1;i<4;i++)
         {
              x.data=i;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

         myfile=fopen("d:\\text.bin","rb+");

         for(i=0;i<3;i++)
         {
              fread(&x,sizeof(x),1,myfile);
              printf("%d\n",x.data);
              fseek(myfile,-sizeof(x),SEEK_CUR);
              x.data=2*x.data;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

     }`

      

but ... my output in stdout file was: 1 2 2

it should be 1 2 3

BUT ... when I added fseek (myfile, 0, SEEK_CUR); after fwrite (& x, sizeof (x), 1, myfile); ... it executes correctly and outputs: 1 2 3

can anyone help me ???

+3


source to share


1 answer


You just need to tell the program to switch write mode to read mode to

fseek(myfile,0,SEEK_CUR); 

      



This is necessary if you just don't get the same result without any changes! or maybe you get an endless loop!

0


source







All Articles