《C语言程序设计教程》实验报告范本.doc
第15次练习-夏7周1 教材练习12-1(p243) 将短句"Programming is fun" 写入某文件,文件名自定。请在此插入源代码# include <stdio.h># include <stdlib.h>int main(void)FILE *fp;if(fp=fopen("f1.txt","w")=NULL)printf("File open error!n");exit(0);fprintf(fp,"%s","Programming is fun");if(fclose(fp)printf("Can not close the file!n");exit(0);return 0;2 教材练习12-2 (p247) 已知一个数据文件f.dat中保存了5个学生的考试成绩,包括学号、姓名和分数,文件内容如下:301101 张文 91301102 陈慧 85301103 王卫东76301104 郑伟 69301105 郭温涛55编程要求:1)将文件的内容读出并显示到屏幕中2)在上述基础上,输出成绩最低和成绩最高的学生的学号、姓名和成绩。# include <stdio.h># include <stdlib.h># include <string.h>int main(void)FILE *fp;int num, maxnum,minnum;char stname10,maxname10,minname10;int score, maxscore = 0, minscore = 100;if(fp=fopen("f.dat","r")=NULL)printf("File open error!n");exit(0);while(! feof(fp)fscanf(fp,"%d%s%d",&num,stname, &score);printf("%d%8s%4dn",num,stname,score);if(score>=maxscore)maxnum=num;strcpy(maxname,stname);maxscore=score;if(score<=minscore)minnum=num;strcpy(minname,stname);minscore=score;printf("成绩最高: %d%8s%4dn",maxnum,maxname,maxscore);printf("成绩最低: %d%8s%4dn",minnum,minname,minscore);if(fclose(fp)printf("Can not close the file!n");exit(0);return 0;3教材练习12-3(p254): 读一个指定的文本文件,显示在屏幕上,如果有大写字母,则改成小写字母再输出,并统计行数。根据回车符统计文件行数。要处理的文件名通过键盘读入字符串指定。测试数据要求至少读入3行包含大写字母和其它字母混合的字符串# include <stdio.h># include <stdlib.h>int main(void)FILE *fp;char ch;char fileName20;int num=0; scanf("%s",fileName);if(fp=fopen(fileName,"r")=NULL)printf("File open error!n");exit(0);while(fscanf(fp, "%c", &ch) !=EOF)if(ch>=A&&ch<=Z) ch=ch-A+a;else if(ch=n) num+;putchar(ch); printf("文件行数:%dn",num);if(fclose(fp)printf("Can not close the file!n");exit(0);return 0;假设在f3.txt里已经有如下左图的内容, 下右图是键入f3.txt运行的结果:4教材练习12-4 从键盘输入一行字符,写到文件f4.txt中,并重新读出,最终在屏幕上显示验证。输入以读到回车符n为结束,读文件时要求用EOF来循环控制。请在此插入源代码# include <stdio.h># include <stdlib.h>int main(void)FILE *fp;char ch;if(fp=fopen("f4.txt","w")=NULL)printf("File open error!n");exit(0);while(ch=getchar() !=n)fputc(ch,fp);fputc(ch,fp);if(fclose(fp)printf("Can not close the file!n");exit(0);if(fp=fopen("f4.txt","r")=NULL)printf("File open error!n");exit(0);while(ch=fgetc(fp) !=EOF)putchar(ch);if(fclose(fp)printf("Can not close the file!n");exit(0);return 0;当运行上述程序后, 键盘输入Hello12345, 运行结果如下左图, 打开f4.txt, 内容如下图右5教材练习12-5 某文件f5.txt中有若干实数,请分别读出,并分别进行加1操作后,存入文件f6.txt中。测试数据可在f1.txt中用记事本输入。请在此插入源代码# include <stdio.h># include <stdlib.h>int main(void)FILE *fp1,*fp2;double x;if(fp1=fopen("f1.txt","r")=NULL)printf("File open error!n");exit(0);if(fp2=fopen("f2.txt","w")=NULL)printf("File open error!n");exit(0);while(! feof(fp1)fscanf(fp1,"%lf",&x);printf("%lf ",x);x=x+1;fprintf(fp2,"%lf ",x);fclose(fp1);fclose(fp2);return 0;当运行上述程序后, 打开f5.txt和f6.txt分别为: (假设f5.txt里面输入了三个实数) 6 浙江大学计算机学院