文档详情

课件chap5.ppt

发布:2017-10-01约1.04万字共49页下载文档
文本预览下载声明
第五讲 文件 例5-6 在磁盘上建立一个新文件5-6.txt,并存储5个学生的信息(包括姓名、成绩),然后将这5个学生的数据输入计算机,并在屏幕上显示出来。 #include stdio.h #include stdlib.h struct student{ char name[20]; int score; }; struct student stu[5],stu2[5]; void main() {int i,j=0; FILE *fp; if((fp=fopen(5-6.txt,w))==NULL) {printf(can not open file\n); exit(0); } for(i=1;i=5;i++) {scanf(%s %d,stu[i].name,stu[i].score); fprintf(fp,%s %d\n,stu[i].name,stu[i].score); } fclose(fp); if((fp=fopen(5-6.txt,r))==NULL) {printf(can not open file\n); exit(0); } for(i=1;i=5;i++) {fscanf(fp,%s %d,stu2[i].name,stu2[i].score); printf(%s %d\n,stu2[i].name,stu2[i].score); } fclose(fp); } 例5-7 在磁盘上建立一个新文件5-7,并存储5个学生的信息(包括姓名、成绩),然后将第1、3、5个学生的数据输入计算机,并在屏幕上显示出来。 #include stdio.h #include stdlib.h struct student{ char name[20]; int score; }; struct student stu[5],stu2[5]; void main() {int i; FILE *fp; if((fp=fopen(5-7,wb))==NULL) {printf(can not open file\n); exit(0); } for(i=0;i5;i++) {scanf(%s %d,stu[i].name,stu[i].score); if(fwrite(stu[i],sizeof(struct student),1,fp)!=1) printf(file write error\n); } fclose(fp); if((fp=fopen(5-7,rb))==NULL) {printf(can not open file\n); exit(0); } for(i=0;i5;i+=2) {fseek(fp,i*sizeof(struct student),0); fread(stu2[i],sizeof(struct student),1,fp); printf(%s %d\n,stu[i].name,stu[i].score); } fclose(fp); } 字符串方式读写函数fgets和fputs 函数fgets( )--从文本文件中读取字符串。 fgets(s, n, fp); s:可以是字符数组名或字符指针;n:指定读入的字符个数;fp:文件指针。 函数被调用时,最多读取n-1个字符,并将读入的字符串存入s所指向内存地址开始的n-1个连续的内存单元中。 当函数读取的字符达到指定的个数,或接收到换行符,或接收到文件结束标志EOF时,将在读取的字符后面自动添加一个’\0’字符;若有换行符,则将换行符保留(换行符在’\0’字符之前);若有EOF,则不保留。 函数返回值 执行成功,返回读取的字符串。 如果失败,则返回空指针,这时,s的内容不确定。 例5-5 /*将字符串“apple”, “grape”, “pear” 写入到磁盘文件f5-5.txt中,然后再从该文件中读出,显示到屏幕。*/ #include stdio.h int main(void) { FILE *fp; int i; char a[ ][80] = {apple, grape, pear}, strout[80]=; if((fp = fopen(f5-5.txt,w)) == NULL){ printf(File open error!\n); exit(0); } for(i = 0;i 3;i++) fputs(a[i], fp); fclose(fp); if((fp = fopen(f5-5.txt,r)) == NULL){ printf(File open error!
显示全部
相似文档