第10章对文件的输入输出.ppt
文本预览下载声明
10.5 文件读写的出错检测 1.ferror函数 ferror函数的一般调用形式为 ferror(fp); 如果返回值为0,表示未出错,否则表示出错 每次调用输入输出函数,都产生新的ferror函数值,因此调用输入输出函数后立即检查 调用fopen时,ferror的初始值自动置为0 10.5 文件读写的出错检测 2. clearerr函数 作用是使文件错误标志和文件结束标志置为0 调用一个输入输出函数时出现错误(ferror值为非零值),立即调用clearerr(fp),使ferror(fp)值变0,以便再进行下一次检测 只要出现文件读写错误标志,它就一直保留,直到对同一文件调用clearerr函数或rewind函数,或任何其他一个输入输出函数 10.3.4 用二进制方式向文件读写一组数据 一般调用形式为: fread(buffer,size,count,fp); fwrite(buffer,size,count,fp); 10.3.4 用二进制方式向文件读写一组数据 buffer:是一个地址 对fread来说,它是用来存放从文件读入的数据的存储区的地址 对fwrite来说,是要把此地址开始的存储区中的数据向文件输出 size:要读写的字节数 count:要读写多少个数据项 fp:FILE类型指针 例10.4 从键盘输入10个学生的有关数据,然后把它们转存到磁盘文件上去。 解题思路: 定义有10个元素的结构体数组,用来存放10个学生的数据 从main函数输入10个学生的数据 用save函数实现向磁盘输出学生数据 用fwrite函数一次输出一个学生的数据 #include stdio.h #define SIZE 10 struct Student_type { char name[10]; int num; int age; char addr[15]; }stud[SIZE]; 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的倍数 当前路径下的文件 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; } 为了验证在磁盘文件“stu.dat”中是否已存在此数据,可以用以下程序从“stu.dat”文件中读入数据,然后在屏幕上输出。 #include stdio.h #include stdlib.h #define SIZE 10 struct Student_type { char name[10]; int num; int age; char addr[15]; }stud[SIZE]; int main( ) {int i; FILE *fp; if((fp=fopen(stu.dat,rb))==NULL) {printf(cannot open file\n); exit(0); } for(i=0;iSIZE;i++) {fread (stud[i],sizeof(struct Student_type),1,fp); printf (“%-10s %4d %4d %-15s\n”, stud[i].name,stud[i].num, stud[i]. age,stud[i].addr); } fclose (fp); return 0; }
显示全部