23-5-15--c++文件基本操作--dog

daniel350-wang / 2023-05-16 / 原文

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

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Dog{
public:
double weight,age;
Dog()=default;
Dog(double _weight,double _age){
weight=_weight;
age=_age;
}
};

int main(){
//二进制方式
Dog dog1(5,10);
ofstream ofile;
ofile.open("dog",ios::out|ios::binary);
ofile.write((const char*)&dog1,sizeof(dog1));
ofile.close() ;
ifstream ifile;
ifile.open("dog",ios::in|ios::binary);
Dog dog2;
ifile.read((char*)&dog2,sizeof(dog2));
cout<<"binarymode: weight:"<<dog2.weight <<" age:"<<dog2.age<<endl ;
ofile.close() ;

//文本方式
ofile.open("dog.txt",ios::out);
ofile<<dog1.weight <<endl<<dog1.age<<endl ;
ofile.close() ;

ifile.open("dog.txt",ios::in);

string buf;
double v[2];
int cnt=0;
while(getline(ifile,buf))
{
v[cnt]=atof(buf.c_str() );
cnt++;
}
Dog dog3(v[0],v[1]);
cout<<"Textmode: weight:"<<dog2.weight <<" age:"<<dog2.age ;
ofile.close() ;
}

运行结果: