字符串以二进制文件

编程入门 行业动态 更新时间:2024-10-24 14:20:04
本文介绍了字符串以二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题是这样的:我有一个名为注册类。它有一个名为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).

更多推荐

字符串以二进制文件

本文发布于:2023-11-30 11:36:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   二进制文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!