fread-fwrite pointer

/****************************to test fwrite functionn***************
*************pointer writer
8-13 song
*****************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define SIZE 3

struct  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 read

8-13 song
*****************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define SIZE 3
struct  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 text1
num=1,name=student1,sex=female1
num=5,name=student2,sex=female2
num=3,name=student3,sex=female3
[root@localhost mmap]# hexdump text1
0000000 0001 0000 7473 6475 6e65 3174 6600 6566
0000010 616d 656c 0031 7473 0005 0000 7473 6475
0000020 6e65 3274 6600 6566 616d 656c 0032 7473
0000030 0003 0000 7473 6475 6e65 3374 6600 6566
0000040 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
*/




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值