How to read/write string type member of a struct using binary file in/out in c++?

后端 未结 2 1174
花落未央
花落未央 2021-01-26 06:42

I have 2 c++ code: one is for write data into a binary file, another is for read that file.

write.cpp code is as below:

#include 

        
相关标签:
2条回答
  • 2021-01-26 07:34

    The only way that comes to mind is to write the following data separately:

    1. Length of the string.
    2. The array of characters of the string.
    3. The age.

    and read them separately.

    Create functions to write/read an instance of Data such that they are aware of each other's implementation strategy.

    std::ostream& write(std::ostream& out, Data const& data)
    {
       size_t len = data.name.size();
       out.write(reinterpret_cast<char const*>(&len), sizeof(len));
       out.write(data.name.c_str(), len);
       out.write(reinterpret_cast<char const*>(&data.age));
       return out;
    }
    
    std::istream& read(std::istream& in, Data& data)
    {
       size_t len;
       in.read(reinterpret_cast<char*>(&len), sizeof(len));
    
       char* name = new char[len+1];
       in.read(name, len);
       name[len] = '\0';
       data.name = name;
       delete [] name;
    
       in.read(reinterpret_cast<char*>(&data.age));
       return in;
    }
    

    and use them similarly to your first approach.

    Instead of using

    people.write(reinterpret_cast<char *>(&person),sizeof(person));
    

    use

    write(people, person);
    

    Instead of using

    people.read(reinterpret_cast<char *>(&person),sizeof(person));
    

    use

    read(people, person);
    
    0 讨论(0)
  • 2021-01-26 07:35

    One problem is that sizeof(person.Name) does not give what you think it does. It always gives the same size (28 bytes in my case) not matter what characters you assign to your person.Name string. This is because of std::string contains at least:

    • a pointer to the actual string
    • other data structure to hold the available size and the size used

    Therefore, you cannot call people.write(reinterpret_cast<char *>(&person),sizeof(person));. The content of your string is not located at &person (its located wherever the pointer in std::string is pointing to)

    So, what happens when you do cout << person.name << endl; after reading it from your file? You've actually read the address (not the content) where person.name's string pointer was pointing to, when you wrote person to people.db. This is of course not a valid memory location, after reading it from your file, again.

    0 讨论(0)
提交回复
热议问题