如何读写二进制文件

如果用getc或putc读写一个结构,那么必须循环通过整个结构,每次循环处理一个字节,这会非常麻烦。

如果使用fputs和fgets,那么遇到null字节就会停止,而在结构中可能含有null字节,所以不能使用它实现读结构的要求。

如果进行二进制I/O操作,每次可以读或者写一个完整的结构。

#include  <stdio.h>
size_t fread(void *restrict ptr,size_t size,sze_t nobj,FILE *restrict fp);
size_t fwrite(const void *restrict ptr,size_t size,size_t nobj,FILE *restrict fp);

我们下面以读写一个结构体为例来说明:

我们要读写的数据结构如下:

//the struct of supplier
struct Supplier
{
  int code;
  char name[nameSize];
  char address[addressSize];
};

//the struct of part
struct Part
{
 int code;
 char name[10];
 int supplierCode[3];
};
下面是将结构体数组以二进制方式写入:

//save the binary file
void save()
{
  FILE *stream;
  if((stream=fopen("parts.dat","wb"))==NULL)
      cout<<"can't open file."<<endl;
  else
    for(int i=0;i<8;i++)
      {
	fwrite(&myPart[i],sizeof(Part),1,stream);
      }
  fclose(stream);

  FILE *stream1;
  if((stream1=fopen("suppliers.dat","wb"))==NULL)
    cout<<"can't open file."<<endl;
  else
  for(int i=0;i<15;i++)
    {
	fwrite(&mySupplier[i],sizeof(Supplier),1,stream1);
    }
  fclose(stream1);
  cout<<"8 part records have been saved."<<endl;
  cout<<"15 supplier records have been saved."<<endl;
}

下面是将我们刚存入的数据读出来:

void verify()
{
  cout<<"Verifying......"<<endl;
  Part testPart[8];
  Supplier testSupplier[15];

  FILE* f1;
  if ((f1=fopen("parts.dat","rb"))==NULL)
    cout<<"can't open file."<<endl;
  else
    for(int i=0;i<8;i++)
      fread(&testPart[i],sizeof(Part),1,f1);
  fclose(f1);

  FILE* f2;
  if ((f2=fopen("suppliers.dat","rb"))==NULL)
    cout<<"can't open file."<<endl;
  else
    for(int i=0;i<15;i++)
      fread(&testSupplier[i],sizeof(Supplier),1,f2);
  fclose(f2);

  cout<<"Parts are"<<endl;
  for(int i=0;i<8;i++)
    cout<<testPart[i].name<<endl;
  cout<<"suppliers are"<<endl;
  for(int i=0;i<15;i++)
    cout<<testSupplier[i].name<<endl;
  cout<<"Thanks."<<endl;
}

注意:其中打开文件时的参数"rb"和"wb"分别表示以二进制的方式读或者写。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值