二進制文件中讀寫結構體

/////////////////////////////////////////////////////////////函數

//老師給咱們分佈裏一個做業,讓咱們定義一個怪物的結構體,ci

//輸入你想建立的數字就能夠建立出相應個數的怪物。it

//而後再輸入每一個怪物的信息並保存到一個文本文件裏面,以供之後讀取。二進制

//這裏我定義了一個結構體,還進行了二進制文件讀寫和存儲fread,fwrite數據

//這裏只是一個createMonster()函數,在main函數裏面調用便可。文件

struct Monster
{
 int ID;
 char name[10];
 char species[10];
 char tpye[10];
};
co

void createMonster(int n)
{
  Monster *monster;
  Monster *ms;
  for (int i = 0;i<n;i++) 
  {
   monster = new Monster[n];
   ms = new Monster[n];
  }
  cout<<"建立怪物成功!"<<endl;
數字

  cout<<"設置怪物的數據:"<<endl;
  cout<<endl;
  for (int i = 0;i<n;i++)
  {
   cout<<"第"<<i<<"個怪物信息:"<<endl;
   cout<<"ID  "<<"名字   "<<"種族:   "<<"戰鬥類型"<<endl;
   cin>>monster[i].ID>>monster[i].name>>monster[i].species>>monster[i].tpye;
  }
  cout<<"輸入完畢!準備保存怪物信息........"<<endl;
  Sleep(10);
new

  FILE* pf;
  if ((pf = fopen("Monster.txt","wb+"))==NULL)
  {
   cout<<"不能打開文件!"<<endl;
  }
結構體

  fwrite(monster,sizeof(Monster),n,pf);
  rewind(pf);

  fread(ms,sizeof(Monster),n,pf);

  for (int i = 0;i<n;i++)
  {
   cout<<ms[i].ID<<endl;
   cout<<ms[i].name<<endl;
   cout<<ms[i].species<<endl;
   cout<<ms[i].tpye<<endl;
  }

  fclose(pf);}

相關文章
相關標籤/搜索