文档详情

C程序设计23--对文件的输入输出讲解.ppt

发布:2017-03-20约1.08万字共99页下载文档
文本预览下载声明
C 程序设计 授课教师 孙向群 fd_jsj@163.com #include stdio.h #include stdlib.h int main() { FILE *fp; char str[3][10]; int i=0; if((fp=fopen(“D:\\CC\\string.dat”, “r”))==NULL) {printf(cant open file!\n);exit(0);} while(fgets(str[i],10,fp)!=NULL) { printf(%s,str[i]); i++; } fclose (fp); return 0; } 不用人为地输出’\n’ 10.3.2 怎样向文件读写一个字符串 10.3.3 用格式化的方式读写文件 一般调用方式为: fprintf(文件指针,格式字符串,输出表列); fscanf (文件指针,格式字符串,输入表列); 如: fprintf (fp,”%d,%6.2f”,i,f); fscanf (fp,”%d,%f”,i,f); 10.3.4 用二进制方式向文件读写一组数据 一般调用形式为: fread(buffer,size,count,fp); fwrite(buffer,size,count,fp); buffer:是一个地址 对fread来说,它是用来存放从文件读入的数据的存储区的地址 对fwrite来说,是要把此地址开始的存储区中的数据向文件输出 size:要读写的字节数 count:要读写多少个数据项 fp:FILE类型指针 10.3.4 用二进制方式向文件读写一组数据 例10.4 从键盘输入10个学生的有关数据,然后把它们转存到磁盘文件上去。 解题思路: 定义有10个元素的结构体数组,用来存放10个学生的数据 从main函数输入10个学生的数据 用save函数实现向磁盘输出学生数据 用fwrite函数一次输出一个学生的数据 10.3.4 用二进制方式向文件读写一组数据 #include stdio.h #define SIZE 10 struct Student_type { char name[10]; int num; int age; char addr[15]; }stud[SIZE]; 10.3.4 用二进制方式向文件读写一组数据 void save( ) { FILE *fp; int i; if((fp=fopen(stu.dat,wb))==NULL) { printf(cannot open file\n); return; } for(i=0;iSIZE;i++) if(fwrite(stud[i], sizeof(struct Student_type), 1,fp)!=1) printf(file write error\n); fclose(fp); } 10+4+4+15=33,实际上开辟36字节,是4的倍数 当前路径下的文件 10.3.4 用二进制方式向文件读写一组数据 int main() { int i; printf(“enter data of students:\n); for(i=0;iSIZE;i++) scanf(%s%d%d%s, stud[i].name,stud[i].num, stud[i].age,stud[i].addr); save( ); return 0; } 10.3.4 用二进制方式向文件读写一组数据 为了验证在磁盘文件“stu.dat”中是否已存在此数据,可以用以下程序从“stu.dat”文件中读入数据,然后在屏幕上输出。 10.3.4 用二进制方式向文件读写一组数据 #include stdio.h #include stdlib.h #define SIZE 10 struct Student_type { char name[10]; int num; int age; char addr[15]; }stud[SIZE]; 10.3.4 用二进制方式向文件读写一组数据 int main( ) {int i; FILE *fp; if((fp=fopen(st
显示全部
相似文档