C语言文件流操作的二进制读写和定位(fwrite、fread、fseek)

二进制写文件中用到fwrite函数,这个函数对文件进行写操作的时候写进去的数据就是二进制的数据包括后面的fread函数,进行读操作的时候也是直接读二进制,这也是在对文件操作时,这两个函数与fprintf和fscanf的区别。读文件操作代码中用到了fseek函数,fseek可以定位到指针指向文件的任意位置,格式:  int fseek(FILE *stream, long offset, int fromwhere);第一个参数代表操作哪个文件,第二个参数是移动的字节数,可以是正负数,负数代表往前数字节,正数代表往后数字节,第三个参数代表从哪个地方开始,可以从开头开始,可以从当前位置开始,也可以从结尾开始。

//二进制文件写文件

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

typedef struct{

    int sno;

    char name[10];

}student;

 

int main ()

{

    FILE * fp;

    int i;

    student stu[5];

   stu[0].sno=201701;strcpy(stu[0].name,"li");

   stu[1].sno=201702;strcpy(stu[1].name,"wang");

   stu[2].sno=201703;strcpy(stu[2].name,"zhang");

   stu[3].sno=201704;strcpy(stu[3].name,"zhao");

   stu[4].sno=201705;strcpy(stu[4].name,"huang");

 

    if((fp = fopen ("myfile","wb"))==NULL)

    {

        printf("cant open the file");

        exit(0);

    }

 

    for(i=0;i<5;i++)

    {

       if(fwrite(&stu[i],sizeof(student),1,fp)!=1)//fwrite执行成功的返回值是fwrite函数的第三个参数

            printf("file writeerror\n");

    }

    fclose (fp);

    return 0;

}



//二进制读文件操作

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

typedef struct{

    int sno;

    char name[10];

}student;

 

int main () {

    FILE * fp;

    student stu;

     long a;

   if((fp=fopen("myfile","rb"))==NULL) //rb代表按照二进制的方式进行读

    {

      printf("cant open the file");

      exit(0);

    }

     //fread函数如果读成功返回的值是fread函数的第三个参数,此时为1                   

    while(fread(&stu,sizeof(student),1,fp)==1)   //如果读到数据,就显示;否则退出

    {

        printf("%d%s\n",stu.sno,stu.name);

    }

     //因为student结构体占14个字节,不知道为什么后面自动加两个字节

     //所以定位按行输出只能定位到每行的行首,即距文件开端16的倍数字节处

    printf("输入您要定位的字节数(只能为0,32,48,64\n");

     scanf("%ld",&a);

     fseek(fp,a,0);

     if(fread(&stu,sizeof(student),1,fp)==1)

     {

         printf("%d%s\n",stu.sno,stu.name);

     }

    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值