简体   繁体   中英

fread() not working after fseek() with fwrite() in C

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 ???

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM