字符串以二进制文件 [英] Strings to binary files

查看:205
本文介绍了字符串以二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是这样的:我有一个名为注册类。它有一个名为trainName,其制定者的字符串属性:

My problem goes like this: I have a class called 'Register'. It has a string attribute called 'trainName' and its setter:

class Register {

 private:
    string trainName;

 public:
    string getTrainName();
};

由于事实上,这是较长,但我想使这个简单。

As a matter of fact, it is longer but I want to make this simpler.

在其他类中,我复制多个注册的对象为二进制文件,previously设置trainName。

In other class, I copy several Register objects into a binary file, previously setting trainName.

Register auxRegister = Register();   
auxRegister.setName("name");

for(int i = 0; i < 10; i++) {

  file.write(reinterpret_cast<char*>(&auxRegister),sizeof(Register));

}

后来,我尝试从二进制文件中检索寄存器:

Later on, I try to retrieve the register from the binary file:

Register auxRegister = Register();

while(!file.eof()) { //I kwnow this is not right. Which is the right way?

    file.read(reinterpret_cast<char*>(&auxRegister), sizeof(Register));
}

它发生在这是行不通的。注册呢,其实,有更多的属性(他们是int)和我找回它们OK,但它不是以字符串的情况。

It occurs it does not work. Register does, in fact, have more attributes (they are int) and I retrieve them OK, but it's not the case with the string.

我是不是做错了什么?二进制文件和字符串时,我应该采取什么考虑?

Am I doing something wrong? Should I take something into consideration when working with binary files and strings?

非常感谢你。

推荐答案

您可以不写串这种方式,因为它几乎可以肯定包含指向一些结构,并不能在所有序列其他二进制的东西。
你需要编写自己的序列化功能,并写入字符串长度+字节(例如)或使用完整的图书馆,例如,的 protobuf的,它可以为你解决问题的序列化

You cannot write string this way, as it almost certainly contains pointers to some structs and other binary stuff that cannot be serialized at all. You need to write your own serializing function, and write the string length + bytes (for example) or use complete library, for example, protobuf, which can solve serializing problem for you.

编辑:见执政官的回答。比我的(即使在此编辑的时候得分较低)要好得多。

edit: see praetorian's answer. much better than mine (even with lower score at time of this edit).

这篇关于字符串以二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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