Writing to a binary file?

Here is the data structure with variables:

struct Part_record
{
    char id_no[3];
    int qoh;
    string desc;
    double price:
};
---
(Using "cin" to input data)
---
Part_record null_part = {"  ", 0,"                         ",0.0};
---
---
file.seekg( -(long)sizeof(Part_record), ios::cur);
file.write( ( char *)&part, sizeof(Part_record) );

Three variables, qoh, Id_no and price, are written out correctly, but the "desc" variable is incorrect. Do I need to initialize Part_record in some other way? Length must be 20 characters.

If you have enough information, please share your tips.

+3
source share
5 answers

std::stringsaves its data in dynamically allocated memory, and not in the structure Part_record.

+3
source

std::string ( STL) . , ; , .

iostream, std::string . part.desc [0], - , :

fwrite(&part.desc[0], part.desc.size());
+1

string ; char[20] , string - , ( , ).

char[20], , 20 . . , 25 , char[26].

, , - , .

0

std::string , , .

, (.. desc.data() desc.size(), ptr .)

0

:

struct Part_record
{
    char id_no[3];
    int qoh;
    string desc;
    double price:
// Block I/O methods
    size_t  Size_On_Stream(void) const
    {
      size_t size = 0;
      size = sizeof(id_no) + sizeof(goh) + sizeof(price);
      size += descr.length() + 1; // +1 for terminating null character
      return size;
    }
    void  Store_To_Buffer(unsigned char *& p_buffer) const
    {
       std::copy((unsigned char *)&id_no[0], (unsigned char *)&id_no[3], p_buffer);
       p_buffer += sizeof(id_no);
       std::copy((unsigned char *)&goh, (unsigned char *)(&goh) + sizeof(goh), p_buffer);
       p_buffer += sizeof(goh);
       std::copy((unsigned char *)&price, (unsigned char *)(&price) + sizeof(price), p_buffer);
       p_buffer += sizeof(price);
       strcpy(p_buffer, descr.str());
       p_buffer += descr.length();
       *p_buffer = 0x00;
       ++p_buffer;
       return;
     }
     void Write_To_Stream(ostream& output) const
     {
       size_t buffer_size = Size_On_Stream();
       unsigned char * buffer = new unsigned char [buffer_size];
       unsigned char * p_buffer = buffer;
       Store_To_Buffer(p_buffer);
       output.write((char *)buffer, buffer_size);
       delete [] buffer;
       return;
      }
};

Since you have floating point values, integer values ​​and text, I strongly suggest using ASCII format or text format such as CSV or XML. Binary versions of numbers (integral and floating point) may be incompatible between platforms, between OS versions and even compiler versions. In addition, variable-length text is a pain to deal with in binary formats.

0
source

Source: https://habr.com/ru/post/1740222/


All Articles