C++map容器里的所有内容以二进制方式保存与读取到文件

原地址 http://www.chinadmd.com/file/w6wscter3u6osooaapvco63u_2.html


读写二进制文件。 

Class 用法.

将map存进二进制文件,高速读写。


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

class STUDENT{
   public:
      string name;
      int age;
};
int main()
{
   map<int,STUDENT> obm, VM;
   int num;
   STUDENT stu;
   num = 23;
   stu.name = "张山";
   stu.age = 55;
   obm.insert(make_pair(num, stu));
   num = 24;
   stu.name = "王五";
   stu.age = 55;
   obm.insert(make_pair(num, stu));
   num = 25;
   stu.name = "什么";
   stu.age = 55;
   obm.insert(make_pair(num, stu));
   num = 26;
   stu.name = "哎呀";
   stu.age = 55;
   obm.insert(make_pair(num, stu));
//显示
   cout << "学号\t姓名\t年龄" << endl;
   map<int,STUDENT>::iterator iter = obm.begin();
   while (iter != obm.end()){
      cout << iter->first << "\t" << iter->second.name << "\t" << iter->second.age << endl; iter++; //保存
   }
   ofstream out("22.txt",ios::binary);
   if (!out.is_open()) {
      cout << "File is open fail!" << endl;
   }
   iter = obm.begin();
   while (iter != obm.end()) {
      out.write((char*)&iter->first,sizeof(int));
      out.write((char*)&iter->second,sizeof(stu));
      iter++;
   }
   out.close(); //读取
   ifstream in("22.txt",ios::binary);
   if (!in.is_open()) {
      cout << "File is open fail!" << endl;
   }
   while (!in.eof()) {
      in.read((char*)&num,sizeof(int));
      in.read((char*)&stu,sizeof(stu));
      VM.insert(make_pair(num,stu));
   }
   in.close(); //显示
   iter = VM.begin();
   while (iter != VM.end()) {
      cout << iter->first << " " << iter->second.name << " " << iter->second.age << endl; iter++;
   }
   return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值