Loading... **实验十一 文件** **一、目的要求** 1、掌握文件以及缓冲文件系统,文件指针的概念; 2、学会使用文件打开,关闭,读,写等文件操作函数; 3、学会用缓冲文件系统对文件进行简单的操作。 **二、实验环境** 硬件平台:计算机CPU主频2.0G以上,内存8G以上; 软件平台:windows7或以上版本,Vscode。 **三、实验内容** 编辑、编译、运行实验指导中给出的程序,并分析输出结果; 1.将一个实型变量f=55.56和一个整型数组a[5]的数据写到磁盘文件TEXT.dat中,然后再读回到另一个实型变量ff及另一个整型数组b[5]中。 要求: 对整型数组a[5]直接初始化方式赋值。 输出实型变量ff(精度为小数点后三位)和数组b[5]的内容。 2.有五个学生,每个学生有三门课的成绩,从键盘键入以下数据(包括学号、姓名、三门课成绩),计算出平均成绩,将原有数据和平均分存放在stuinfo.tex文件中。 要求: (1)设五名学生的学号、姓名、三门课成绩如下: 99101 Wang 83 92 67 99103 Li 67 80 90 99106 Fun 75 91 99 99110 Ling 100 50 62 99113 Yuan 55 68 71 (2)在屏幕上输出stuinfo.txt文件的内容。 # 代码1 ```C #include <stdio.h> int main(int argv,char *argc[]){ FILE *fp; int a[5]={1,2,3,4,5},b[5]; double f=55.56,ff; if((fp=fopen("TEXT.dat","w"))==NULL){ printf("Open the file failure, exit...\n"); return 0; } fprintf(fp,"%f %d %d %d %d %d\n",f,a[0],a[1],a[2],a[3],a[4]); fclose(fp); if((fp=fopen("TEXT.dat","r"))==NULL){ printf("Open the file failure, exit...\n"); return 0; } fscanf(fp,"%lf%d%d%d%d%d",&ff,b,b+1,b+2,b+3,b+4); fclose(fp); printf("%.3f\n%d %d %d %d %d\n",ff,b[0],b[1],b[2],b[3],b[4]); return 0; } ``` # 代码2 ```C #include<stdio.h> #include<stdlib.h> #define N 5 struct Student{ char id[10]; char name[10]; float score[3]; float ave; }stu[N]; void input(void){ int i,j; for(i=0;i<N;i++){ printf("输入第%d个学生信息:\n",i+1); scanf("%s %s %f %f %f",&stu[i].id,&stu[i].name,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]); stu[i].ave=(stu[i].score[0]+stu[i].score[1]+stu[i].score[2])/3; } } void wri(void){ FILE *fp; int i; fp=fopen("stuinfo.txt","w"); for(i=0;i<N;i++) if(fwrite(&stu[i],sizeof(struct Student),1,fp)!=1){ printf("\n写入错误!!!\n"); exit(0); } fp=fopen("stuinfo.txt","r"); puts("----------------------------------------------"); puts("学号\t姓名\t成绩1\t成绩2\t成绩3\t平均分"); puts("----------------------------------------------"); for(i=0;i<N;i++){ fread(&stu[i],sizeof(struct Student),1,fp); printf("%s\t%s\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].id,stu[i].name,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].ave); } fclose(fp); } int main(){ input(); wri(); return 0; } ``` 最后修改:2023 年 08 月 05 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏