5.18打卡

一、实验内容

定义一个Dog类,包括体重和年龄两个数据成员及其成员函数,声明一个实例dog1,体重5,年龄10,使用I/O流把dog1的状态写入磁盘文件。再声明一个实例dog2,通过读取文件dog1的状态赋给dog2。分别用文本方式和二进制方式操作文件。

二、实验代码

#include<bits/stdc++.h>
using namespace std;
class Dog
{
public:
 double weight;
 int age;
 } ;
 
 struct ConfigManager
 {
  public:
   ConfigManager(const char* configfile = "bitsserver.config")
    :_configfile(configfile)
    {
    }
  void WriteBin(const Dog& info)
  {
   ofstream ofs(_configfile, ifstream::out | ifstream::binary);
   ofs.write((const char*)&info, sizeof(Dog));
   ofs.close();
  }
  void ReadBin(Dog& info)
  {
   ifstream ifs(_configfile, ifstream::in | ifstream::binary);
   ifs.read((char*)&info, sizeof(Dog));
   ifs.close();
  }
  
  void WriteText(const Dog& info)
  {
   ofstream ofs(_configfile);
   ofs << info.age << endl;
   ofs << info.weight << endl;
   ofs.close();
  }
  void ReadText(Dog& info)
  {
   ifstream ifs(_configfile);
   ifs >> info.age;
   ifs >> info.weight;
   ifs.close();
  }
 private:
  string _configfile; 
 
 };
 int main()
 {
  ConfigManager cfgMgr;
  Dog dog1;
  Dog dog2;
  dog1.weight = 5;
  dog1.age = 10;
  //文本 
  cfgMgr.WriteText(dog1);
  cfgMgr.ReadText(dog2);
  cout << dog2.age << endl;
  cout << dog2.weight << endl;
  //二进制 
  cfgMgr.WriteBin(dog1);
  cfgMgr.ReadBin(dog2);
  cout << dog2.age << endl;
  cout << dog2.weight << endl; 
  
  return 0; 
 }

三、测试截图

 

 

posted @ 2023-05-18 22:10  yblll  阅读(22)  评论(0)    收藏  举报