hello ,
I have a simple problem a wanaa print form Random File
but the last printed twice???
this is the input
Enter the id :1
Enter the gpa :1.2
Enter the id :2
Enter the gpa :2.4
Enter the id :3
Enter the gpa :3.5
the size is : 3
the id is : 1 the gpa is: 1.20
the id is : 2 the gpa is: 2.40
the id is : 2 the gpa is: 2.40 /// why twice?
Press any key to continue
the code
Code:
#include<stdio.h>
/*********** Data ***********/
typedef struct {
int id;
float gpa;
}data;
/*********** The functions ***********/
void read(data*);
void print(FILE*);
/*********** Main ***********/
int main(){
data R;
FILE *f;
int i;
if((f=fopen("f.dat","w"))==NULL)
printf("sorry i can not open the file\n");
else{
fseek(f,sizeof(data),SEEK_SET);
for(i=1;i<=3;i++){
read(&R);
fseek(f,sizeof(data)*(i-1),SEEK_SET);
fwrite(&R,sizeof(data),1,f);
}
}
print(f);
return 0;
}
/*********** Read ***********/
void read(data *R){
printf("Enter the id :");
scanf("%d",&R->id);
printf("\n");
printf("Enter the gpa :");
scanf("%f",&R->gpa);
printf("\n");
}
/*********** Print ***********/
void print(FILE *f){
data R;
int n=0,i;
if((f=fopen("f.dat","r"))==NULL)
printf("sorry i can not open the file\n");
else{
fseek(f,sizeof(data),SEEK_END);
n=ftell(f)/sizeof(data);
printf("the size is : %d\n",n);
for(i=1;i<=n;i++){
fseek(f,sizeof(data)*(i-1),SEEK_SET);
fread(&R,sizeof(data),1,f);
printf("the id is : %d the gpa is: %.2f \n",R.id,R.gpa);
}
fclose(f);
}
}
/*********** End ***********/