如何读写二进制文件

来源:互联网 发布:javascript 设置css 编辑:程序博客网 时间:2024/06/09 22:05

如果用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 supplierstruct Supplier{  int code;  char name[nameSize];  char address[addressSize];};//the struct of partstruct Part{ int code; char name[10]; int supplierCode[3];};
下面是将结构体数组以二进制方式写入:

//save the binary filevoid 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 0