Error when running a simple program
hi all,
this a simple program in FILES, the program read 3 data and saved in FILE and call the function print to print the FILE
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 *f1;
int i;
if((f1=fopen("f1.dat","w"))==NULL)
printf("sorry i can not open the file\n");
else{
for(i=0;i<3;i++){
read(&R);
fprintf(f1,"%d %.2f",R.id,R.gpa);
}
fclose(f1);
print(f1);
}
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;
if((f=fopen("f.dat","r"))==NULL)
printf("sorry i can not open the file\n");
else{
while(!feof(f)){
fscanf(f,"%d %.2f",&R.id,&R.gpa);
printf("The id is: %d the gpa is: %.2f",R.id,R.gpa);
}
fclose(f);
}
}
/*********** End ***********/
the out is
Enter the id :1
Enter the gpa :2.9
Enter the id :2
Enter the gpa :3.8
Enter the id :3
Enter the gpa :4.5
sorry i can not open the fil //why can not open??????
Press any key to continue