Code:
int main()
{
int i=0;
int flag = FALSE;
int flag2;
int ans;
INFO data2[5];
FILE *fp2;
double root , R;
double check , check2;
double f;
char ans2;
if (( fp2 = fopen(BINFILE, "wb+")) != NULL )
{
printf("Do you want to choose previously inputted values? (y/n)\n");
fflush(stdin);
scanf("%c",&ans2);
if (ans2 == 'y')
flag = TRUE;
fp2 = fopen(BINFILE, "wb+");
}
while(i < 5 && flag==FALSE)
{
do
{
flag2 = TRUE;
printf("Please enter the value for L:\n");
scanf("%lf",&data2[i].l);
printf("Please enter the value for C:\n");
scanf("%lf",&data2[i].c);
printf("Please enter the value for the battery voltage:\n");
scanf("%lf",&data2[i].v);
printf("Please enter the value for the dissipation time td:\n ");
scanf("%lf",&data2[i].td);
printf("Please enter the value for the percentage of the\n"
"original charge pc to reach within td\n");
scanf("%lf",&data2[i].pc);
R = (-2* data2[i].l * log(data2[i].pc))/data2[i].td;
check = 1/(data2[i].l*data2[i].c);
check = check - pow((R/(2*data2[i].l)),2) ;
check2 = sqrt(check);
f = check2/(2*pi);
f= 50/f;
if(check < 0)
{
flag2 = FALSE;
printf("Invalid input , Please enter a bigger value for td\n");
}
if(f < data2[i].td)
{
flag2 = FALSE;
printf("Frequency too high; plot may be distorted\n");
}
}while(flag2 == FALSE);
fwrite(&data2[i].l, sizeof(double), 1, fp2);
fwrite(&data2[i].c, sizeof(double), 1, fp2);
fwrite(&data2[i].v, sizeof(double), 1, fp2);
fwrite(&data2[i].td, sizeof(double), 1, fp2);
fwrite(&data2[i].pc, sizeof(double), 1, fp2);
//fwrite(&data2, sizeof(data2), 1 ,fp2);
i++;
printf("do you want to \n"
"1. enter a new set of values(max 5)\n"
"or\n"
"2.choose a saved set of values\n");
scanf("%d",&ans);
if (ans == 2)
flag = TRUE;
}
printf("which set of values do you want to use?\n");
scanf("%d",&ans);
rewind(fp2);
// compensate for zero element.
if ( ans-1 > 6)
{
printf("out of bounds\n");
return -1;
}
else
{
fread(&data2[ans-1].l, sizeof(double), 1, fp2);
fread(&data2[ans-1].c, sizeof(double), 1, fp2);
fread(&data2[ans-1].v, sizeof(double), 1, fp2);
fread(&data2[ans-1].td, sizeof(double), 1, fp2);
fread(&data2[ans-1].pc, sizeof(double), 1, fp2);
}
printf("%lf\n",data2[ans-1].l);
findRoot(data2,ans,&root);
fclose(fp2);
return 0;
}
How can I prevent data loss after closing and reopening the file?