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