fread-fwrite pointer

来源:互联网 发布:echarts实时更新数据 编辑:程序博客网 时间:2024/05/22 06:10
/****************************to test fwrite functionn****************************pointer writer8-13 song*****************************************************************/#include<stdio.h>#include<stdlib.h>#define SIZE 3struct  student{int num;char *name;char *sex;}stu;int main(int argc,char* argv[]){struct student stu[SIZE]={{1,"student1","female1"},{5,"student2","female2"},{3,"student3","female3"}};FILE *fp;char ch;int i;if((fp=fopen(argv[1],"wb"))==NULL){printf("cannot open the file");exit(0);}for (i= 0;i<SIZE;i++){if(fwrite(&stu[i].num,sizeof( stu[i].num),1,fp)!=1)printf("file write error\n");if(fwrite(stu[i].name,10,1,fp)!=1)printf("file write error\n");if(fwrite(stu[i].sex,10,1,fp)!=1)printf("file write error\n");}fclose(fp);}
/****************************to test fwrite functionn****************************pointer read8-13 song*****************************************************************/#include<stdio.h>#include<stdlib.h>#define SIZE 3struct  student{int num;char *name;char *sex;}stu;int main(int argc,char* argv[]){struct student stu[SIZE];stu[0].name=malloc(10);stu[1].name=malloc(10);stu[2].name=malloc(10);stu[0].sex=malloc(10);stu[1].sex=malloc(10);stu[2].sex=malloc(10);FILE *fp;char ch;int i;if((fp=fopen(argv[1],"rb"))==NULL){printf("cannot open the file");exit(0);}for (i= 0;i<SIZE;i++){if(fread(&stu[i].num,4,1,fp)!=1)  printf("file write error\n");if(fread(stu[i].name,10,1,fp)!=1)  printf("file write error\n");if(fread(stu[i].sex,10,1,fp)!=1)  printf("file write error\n");printf("num=%d,name=%s,sex=%s\n",stu[i].num,stu[i].name,stu[i].sex);}fclose(fp);}
[root@localhost mmap]# ./fread_test text1num=1,name=student1,sex=female1num=5,name=student2,sex=female2num=3,name=student3,sex=female3[root@localhost mmap]# hexdump text10000000 0001 0000 7473 6475 6e65 3174 6600 65660000010 616d 656c 0031 7473 0005 0000 7473 64750000020 6e65 3274 6600 6566 616d 656c 0032 74730000030 0003 0000 7473 6475 6e65 3374 6600 65660000040 616d 656c 0033 6277                    0000048/*写入时,结构体里面有指针的话,要将指针对应的内容写入写入文件,而不是将指针写入文件,所以不能向上篇那样直接fwrite(&stu[i],sizeof(struct student),1,fp)而是要拆开结构体,分而治之......貌似比用数组麻烦些读出时,要先给stu[0],[1],[2]的name指针, sex指针分配指向空间,否则在fread(stu[i].sex,10,1,fp)时,会segmentation faulse,此时指针不知道指到哪了,将读出的这10个字节的数据放到一个“可能不安全的”地方,运气不好就会segmentation faulse,或者coledump*/