在移动位置指针之后,即可用前面介绍的任一种读写函数进行读写。由于一般是读写一个数据据块,因此常用fread和fwrite函数。下面用例题来说明文件的随机读写。
【例1】在学生文件stu_list中读出第二个学生的数据。- #include<stdio.h>
- struct stu{
- char name[10];
- int num;
- int age;
- char addr[15];
- }boy,*qq;
- main(){
- FILE *fp;
- char ch;
- int i=1;
- qq=&boy;
- if((fp=fopen("stu_list","rb"))==NULL){
- printf("Cannot open file strike any key exit!");
- getch();
- exit(1);
- }
- rewind(fp);
- fseek(fp,i*sizeof(struct stu),0);
- fread(qq,sizeof(struct stu),1,fp);
- printf("\n\nname\tnumber age addr\n");
- printf("%s\t%5d %7d %s\n",qq->name,qq->num,qq->age,qq->addr);
- }
复制代码
文件stu_list已由【例1】的程序建立,本程序用随机读出的方法读出第二个学生的数据。程序中定义boy为stu类型变量,qq为指向boy的指针。以读二进制文件方式打开文件,程序第19行移动文件位置指针。其中的i值为1,表示从文件头开始,移动一个stu类型的长度,然后再读出的数据即为第二个学生的数据。
|
|