Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a binary file?

Tags:

c++

file

binary

Here is 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) );

The three variables, qoh, Id_no & price, write out correctly, but the "desc" variable is not right. Do I need to initialize Part_record some other way? It should be 20 characters in length.

If you have enough info here, please share your advice.

like image 435
rick irby Avatar asked Jun 19 '26 12:06

rick irby


2 Answers

std::string keeps its data in dynamically allocated memory, not in structure Part_record.

like image 164
Kirill V. Lyadvinsky Avatar answered Jun 21 '26 01:06

Kirill V. Lyadvinsky


You can't write std::string objects (or any of the STL containers) to a file in this way. They contain internal pointers to their data which is allocated dynamically; you'll wind up writing pointer addresses to your file, instead of the contents of the string.

I'd recommend using the iostream library if you need to write std::string data to a file. Failing that, you can access the character data directly with part.desc[0] to achieve something similar to what you're attempting:

fwrite(&part.desc[0], part.desc.size());
like image 43
meagar Avatar answered Jun 21 '26 01:06

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!