C ++读写同一类的多个对象 [英] C++ Read and write multiple objects of same class

查看:77
本文介绍了C ++读写同一类的多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

airport air(1,2,3); //an airport constructor
ofstream myfile;
myfile.open("rishab",ios::app||ios::binary);
myfile.write((char*)air,sizeof(airport);
myfile.close();

在我的程序中多次调用了这些命令,以获取许多机场的信息.基本上,二进制文件充满了机场.稍后,我需要将所有这些机场读入数组.如何读取文件,以便获得一系列的机场.

Such commands are called multiple times in my program to get info of many airports. Basically the binary file is full of airports. I need to read all these airports into an array later on. How do I read the file so that I get the array of airports.

很抱歉,这个问题太基本了.我在高中时正在学习有关指针和最短路径图的信息.

Apologies if this question is too basic. I am in high school learning about pointers and shortest path graphs.

推荐答案

您要尝试的是序列化.这种序列化对象的方法不稳定,并且高度取决于飞机场是什么.最好使用显式序列化.

What you are trying to do is serialization. This way of serializing objects is not stable, and highly depends on what airport is. It's better to use explicit serialization.

此处描述了什么是序列化以及为什么要序列化是这样的.

Here's a description of what serialization is and why is it made this way.

MessagePack 中,典型的序列化反序列化方案看起来像这个:

In MessagePack a typical serialization-deserialization scenario would look like this:

struct airport {
 std::string name; //you can name your airports here
 int planeCapacity;
 int acceptPlanesFrom;
 MSGPACK_DEFINE(name,planeCapacity,acceptPlanesFrom);
};

...

// define your airports
std::vector<airport> airports;
airport a={"BLA",1,2};
airport b={"BLB",3,4};
airports.push_back(a);
airports.push_back(b);

// create a platform-independent byte sequence from your data
msgpack::sbuffer sbuf;
msgpack::pack(sbuf, airports) ;
std::string data=sbuf.data();//you can write that into a file

msgpack::unpacked msg;
// get your data safely back
msgpack::unpack(&msg, sbuf.data(), sbuf.size());
msgpack::object obj = msg.get();

std::cout<<obj<<std::endl;

// now convert the bytes back to your objects
std::vector<airport> read_airports;
obj.convert(&read_airports);
std::cout<<read_airports.size()<<std::endl;

带有控制台输出:

[["BLA", 1, 2], ["BLB", 3, 4]]
2

  • 一些 更多
  • 这篇关于C ++读写同一类的多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆