简体   繁体   English

C ++结构二进制文件

[英]C++ struct binary file

Hello guys I am new to c++ programming I have saved struct in binary file.. But when try to read it application is crashing Here is my code 大家好,我是C ++编程的新手,我已经将struct保存在二进制文件中。但是当尝试读取它时,应用程序崩溃了这是我的代码

struct Person
{
    string name;
    int age;

};
void main()
{
    Person p;
    ifstream is("person.data",ios::binary);
    is.read((char*)&p,sizeof(p));


}

You're using sizeof(p) . 您正在使用sizeof(p)

The string class is of variable length. string类的长度可变。 This means it is essentially a struct with a pointer in it to some other characters in the heap. 这意味着它本质上是一个结构,里面有一个指向堆中其他字符的指针。 Attempting to read the string in via struct won't work. 尝试通过struct读取字符串不起作用。 You have to put all the characters in the struct itself, or it will just read in a (now-dead) pointer to somewhere in the heap and likely cause a segmentation fault. 您必须将所有字符放到结构本身中,否则它将只读取(现在已失效)指向堆中某处的指针,并可能导致分段错误。

Try this: 尝试这个:

struct Person
{
    char name[40];
    int age;

};
void main()
{
    Person p;
    ifstream is("person.data",ios::binary);
    is.read((char*)&p,sizeof(p));
}

Then use c string functions instead of C++ ones found in cstring or string.h . 然后使用c字符串函数代替cstringstring.h的C ++函数。

Honestly, though, you may want to listen to @πάντα ῥεῖ . 不过,老实说,您可能想听@πάνταῥεῖ。 You're trying to serialize C structs. 您正在尝试序列化 C结构。 Reading data in via struct is a very "C" thing to do, but you're mixing "C++" classes into that. 通过struct读取数据是非常“ C”的事情,但是您要在其中混入“ C ++”类。 The two paradigms don't mix very well. 这两种范式不能很好地融合在一起。 BOOST has a serialization library , if you really want to serialize C++ classes I would start there. BOOST有一个序列化库 ,如果您真的想序列化C ++类,我将从那里开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM