【问题标题】:c++ serialization of a structurec++ 序列化结构
【发布时间】:2015-08-10 12:55:59
【问题描述】:

在编译这个简单的代码时:

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

class Example
{
    public:
        char  charo;
        int   into;
};

int main()
{
    Example one,two;

    one.charo = 'X'; one.into = 2;

    //WRITING
    ofstream file;
    file.open("my.prx", ios_base::binary);
    if(file.good()) file.write((char*)&one, sizeof(Example));
    else cout << "ERROR WHILE OPENING FILE" << endl;
    file.close();

    //READING
    file.open("my.prx", ios_base::binary);
    if(file.good())
    file.read((char*)&two, sizeof(Example));
    else cout << "ERROR WHILE OPENING FILE" << endl;
    file.close();

    //PRINTING
    cout << "CHAR: " << two.charo << endl;
    cout << "INT: " << two.into << endl;

}

我收到此错误消息:

g++ -o test1 main.c main.c: 在函数'int main()'中: main.c:43:7: 错误:“std::ofstream”没有名为“read”的成员
file.read((char*)&two, sizeof(Example));

我该如何解决? 我的下一步将是制作一个更复杂的对象来保存:

Class Memory{
    t_monitor monitors[MAX_MONITORS];
    t_status status[MAX_STATUS]; 
    t_observer observers[MAX_OBSERVERS];
    Var * first_var;
    int tot_observers;
    int tot_status;
    int tot_monitors;   
};

如您所见,还有一个列表...

【问题讨论】:

  • 我会使用现有的解决方案,例如boost serialization,而不是重新发明轮子......
  • ofstream 中的o 代表输出

标签: c++ object serialization


【解决方案1】:

ofstream 是一个输出文件流。它用于输出,不能“读取”。

请改用fstream

【讨论】:

    【解决方案2】:

    使用ifstream读取ostream用于输出。

    你可以这样做

    std::ifstream fileRead( "my.prx",std::ifstream::binary );
    if(fileRead)
    fileRead.read((char*)&two, sizeof(Example));
    else cout << "ERROR WHILE OPENING FILE" << endl;
    fileRead.close();
    

    【讨论】:

      【解决方案3】:

      仅输出[ofstream][1]。一种易读的方法是使用变量ofstream ofileifstream ifile。这样,从声明和名称中可以清楚地看到用法。如果代码增长,这可能会有所帮助。

      另一种方法是使用两用 fstream,但这会使某些操作变得不明确。

      当然,这些天来,您最好还是使用某种序列化库。首先,选择您的公司或团队已经使用的库,然后,如果该库不合适,请选择现代库,例如 Boost 或我最喜欢的 Cereal

      【讨论】:

      • 你有没有例子展示了如何使用 boost 来序列化一个类似于我的 Memory 的类(带有数组和列表)?
      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多