Strings to binary files

前端 未结 2 1171
隐瞒了意图╮
隐瞒了意图╮ 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: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 buffer( new char[length + 1] );
    file.read( buffer, length );
    
    buffer[length] = '\0'; // NULL terminate the string
    Register auxRegister = Register();
    
    auxRegister.setName( buffer );
    

提交回复
热议问题