3

In my program i make a binary file contains structs (each struct contains one integer)...and i put 3 structs in the file...i want first to create the file...then close it..then reopen it as "rb+" mode...and i want to read the structs from the file and change its value (member data) and rewrite it at 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 is run correctly and output : 1 2 3

can any one help me ???

1
  • 2
    Tested your code and got 1, 2, 3 as expected. Also the file contained 2, 4, 6 after the run.
    – Flovdis
    May 29, 2015 at 11:03

1 Answer 1

0

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

fseek(myfile,0,SEEK_CUR); 

It is necessary if you don't, you just get the same result with no change at all, or you might get an infinite loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.