64,637
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Sprite
{
private:
std::string profession;//职业
std::string weapon;//武器
static int count;//个数
public:
Sprite(){}
Sprite(std::string profession,std::string weapon):profession(profession),weapon(weapon)
{
}
void showSprite();//显示精灵信息
};
int Sprite::count=0;
void Sprite::showSprite()
{
++count;
std::cout<<"精灵"<<count<<" 职业:"<<profession<<" 武器:"<<weapon<<std::endl;
}
void write_bin()
{
Sprite sprite[3] =
{
Sprite("法师", "魔杖"),
Sprite("战士", "屠龙宝刀"),
Sprite("道士","倚天剑")
};
//打开文件
ofstream ofile("file.dat", ios::binary | ios::ate);
if(!ofile)
{
cout<<"打开文件失败!"<<endl;
exit(1);
}
for(int i=0; i</*sizeof(sprite)/sizeof(sprite[0])*/3; i++)
{
ofile.write( (char*)&sprite[i], sizeof(sprite[i]));
ofile.flush();
}
//关闭文件
ofile.close();
}
void read_bin()
{
Sprite sprite[3];
ifstream ifile("file.dat", ios::binary);
if(!ifile)
{
cout<<"打开文件失败!"<<endl;
exit(1);
}
ifile.seekg(/*i*sizeof(Sprite)*/0, ios_base::beg);
for(int i=0; i<3; i++)
{
ifile.read((char*)&sprite[i], sizeof(sprite[i]));
sprite[i].showSprite();
}
ifile.close();
}
int _tmain(int argc, _TCHAR* argv[])
{
write_bin();
read_bin();
while(1);
return 1;
}