1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h>
struct stu { char name[10]; int age; };
int main(void) { struct stu mystu[3]={{"Jim",14},{"Jam",15},{"Lily",19}}; struct stu mystuout; FILE *fp; extern int errno; char file[]="record.txt"; int i,j; long k; fpos_t pos1,pos2; fp=fopen(file,"w"); if(fp==NULL) { printf("cant't open file %s.\n",file); printf("errno:%d\n",errno); printf("ERR :%s\n",strerror(errno)); return(1); } else { printf("%s was opened.\n",file); } i=fwrite(mystu,sizeof(struct stu),3,fp); printf("%d students was written.\n",i); fclose(fp);
fp=fopen(file,"r"); if(fp==NULL) { printf("cant't open file %s.\n",file); printf("errno:%d\n",errno); printf("ERR :%s\n",strerror(errno)); return(1); }
k=ftell(fp); printf("当前指针位置为%ld .\n",k);
fseek(fp,1*sizeof(struct stu),SEEK_SET); fgetpos(fp,&pos1); printf("移动指针后的当前指针位置为%f .\n",(float)pos1.__pos); j=fread(&mystuout,sizeof(struct stu),1,fp); printf("%d students was read.\n",j); printf("NAME:%s\tAGE:%d\n",mystuout.name,mystuout.age);
k=ftell(fp); printf("读出记录后的当前指针位置为%ld .\n",k);
j=fread(&mystuout,sizeof(struct stu),1,fp); printf("%d students was read.\n",j); printf("NAME:%s\tAGE:%d\n",mystuout.name,mystuout.age);
pos2.__pos=(long)(1*sizeof(struct stu)); fsetpos(fp,&pos2); k=ftell(fp); printf("再次移动指针后的当前指针位置为%ld .\n",k);
j=fread(&mystuout,sizeof(struct stu),1,fp); printf("%d students was read.\n",j); printf("NAME:%s\tAGE:%d\n",mystuout.name,mystuout.age);
k=ftell(fp); printf("再次读记录后的当前指针位置为%ld .\n",k);
fclose(fp);
}
|