C++二进制文件读写

要求:

  •   用fstream类创建并打开二进制文件
  •   在文件中存入int,double 5 个基本数据类型
  •   自定义类,并在文件中存入一个类对象
  •   从文件中读取所有基本数据类型
  •   从文件中读取第3个基本类型数据
  •        从文件中读取类对象并使用
    #include<iomanip>
    #include <fstream>
    #include<iostream>
    #include<cstring>
    using namespace std;
    class Time {
    public:
    	int year;
    	int month;
    	void Display()
    	{
    		cout<<year<<" "<<month;
    	}
    };
    int main()
    {
    	//用fstream创建并打开文件
    	fstream OutFile("binaryy.dat", ios::out| ios::in| ios::binary);
    	//写入基本数据类型
    	int a;float b;double c;char d;bool e;
    		a=1; b=1.34; c=1.3415826; d='p'; e=0;
    		OutFile.write((char *)&a,sizeof(a));
    		OutFile.write((char *)&b,sizeof(b));
    		OutFile.write((char *)&c,sizeof(c));
    		OutFile.write((char *)&d,sizeof(d));
    		OutFile.write((char *)&e,sizeof(e));
    	//写入类对象
    		Time t;
    		cin>>t.year>>t.month;
    		OutFile.write((char *) &t, sizeof(t));
    	OutFile.close();
    	fstream inFile("binaryy.dat", ios::in | ios::binary);
    	if (!inFile)
    	{
    		cout << "error" << endl;
    		return 0;
    	}
    	//int a;float b;double c;char d;bool e;
    	//读取所有基本类型
    	inFile.read((char *)&a,sizeof(a));
    		//cout<<a<<endl;
    	inFile.read((char *)&b,sizeof(b));
    		//cout<<b<<endl;
    	inFile.read((char *)&c,sizeof(c));
    		//cout<<c<<endl;
    	inFile.read((char *)&d,sizeof(d));
    		//cout<<d<<endl;
    	inFile.read((char *)&e,sizeof(e));
    		//cout<<e<<endl;
    	cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<endl;
    	//读取类对象
    	inFile.read((char *)&t,sizeof(t));
    		cout << t.year << " " << t.month << endl;
    	//读取第三个基本类型
    	double tmp;
    	inFile.seekg(sizeof(int)+sizeof(float),ios::beg);
    	//while(inFile.get(tmp))	cout<<tmp;
    	inFile.read((char *)&tmp,sizeof(double));
    	cout<<tmp<<endl;
    	//使用类对象
    	t.Display();
    	inFile.close();
    	return 0;
    }

结果如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值