Strings to binary files

前端 未结 2 1064
隐瞒了意图╮
隐瞒了意图╮ 2021-01-28 18:36

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

class Register {

 private:
    str         


        
相关标签:
2条回答
  • 2021-01-28 18:40

    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).

    0 讨论(0)
  • 2021-01-28 18:53

    The std::string class contains a pointer to a buffer where the string is stored (along with other member variables). The string buffer itself is not a part of the class. So writing out the contents of an instance of the class is not going to work, since the string will never be part of what you dump into the file, if you do it that way. You need to get a pointer to the string and write that.

    Register auxRegister = Register();   
    auxRegister.setName("name");
    auto length = auxRegister.size();
    
    for(int i = 0; i < 10; i++) {
      file.write( auxRegister.c_str(), length );
      // You'll need to multiply length by sizeof(CharType) if you 
      // use a wstring instead of string
    }
    

    Later on, to read the string, you'll have to keep track of the number of bytes that were written to the file; or maybe fetch that information from the file itself, depending on the file format.

    std::unique_ptr<char[]> buffer( new char[length + 1] );
    file.read( buffer, length );
    
    buffer[length] = '\0'; // NULL terminate the string
    Register auxRegister = Register();
    
    auxRegister.setName( buffer );
    
    0 讨论(0)
提交回复
热议问题