65,210
社区成员
发帖
与我相关
我的任务
分享//Create a text file with 10 records of the form:
//Model, string (10 characters),
//Cost (double),
//plate (6 characters) and
//customer ID (integer).
//Use a structure to record the data into the file.
//Your program will create this file,
//close it and then reopen to print the first and the last fields of these 10 records.
#include <stdio.h>
struct form {
char Model [11];
double Cost ;
char plate [ 7];
int customerID ;
} rs[10],fs[10]={
{"Modle0",0.0,"plate0",0},
{"Modle1",1.0,"plate1",1},
{"Modle2",2.0,"plate2",2},
{"Modle3",3.0,"plate3",3},
{"Modle4",4.0,"plate4",4},
{"Modle5",5.0,"plate5",5},
{"Modle6",6.0,"plate6",6},
{"Modle7",7.0,"plate7",7},
{"Modle8",8.0,"plate8",8},
{"Modle9",9.0,"plate9",9},
};
FILE *f;
int i;
int main() {
f=fopen("forms.txt","w");
for (i=0;i<10;i++) {
fprintf(f,"%s\n" ,fs[i].Model );
fprintf(f,"%lg\n",fs[i].Cost );
fprintf(f,"%s\n" ,fs[i].plate );
fprintf(f,"%d\n" ,fs[i].customerID);
}
fclose(f);
f=fopen("forms.txt","r");
for (i=0;i<10;i++) {
fscanf(f,"%10s", rs[i].Model );
fscanf(f,"%lf" ,&rs[i].Cost );
fscanf(f,"%6s" , rs[i].plate );
fscanf(f,"%d" ,&rs[i].customerID);
}
fclose(f);
i=0;
printf("rs[%d].Model :%s\n" ,i,rs[i].Model );
printf("rs[%d].Cost :%lg\n",i,rs[i].Cost );
printf("rs[%d].plate :%s\n" ,i,rs[i].plate );
printf("rs[%d].customerID:%d\n" ,i,rs[i].customerID);
i=9;
printf("rs[%d].Model :%s\n" ,i,rs[i].Model );
printf("rs[%d].Cost :%lg\n",i,rs[i].Cost );
printf("rs[%d].plate :%s\n" ,i,rs[i].plate );
printf("rs[%d].customerID:%d\n" ,i,rs[i].customerID);
return 0;
}
//rs[0].Model :Modle0
//rs[0].Cost :0
//rs[0].plate :plate0
//rs[0].customerID:0
//rs[9].Model :Modle9
//rs[9].Cost :9
//rs[9].plate :plate9
//rs[9].customerID:9
//