[C++] Using seekp to overwrite binary data?

I need to write copies of a structure to a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Book{
    string bookTitle;
    string ISBN;
    string author;
    string publisher;
    string dateAdded;
    int qty;
    double wholesale;
    double retail;
};

...

fstream fileout("file.dat", ios::out | ios::binary);

Book book1, book2;
fileout << book1 << book2;


The question is whether or not there is a same way to modify one of these records, even if I had 20? My thought was that having multiple strings, there's no way to tell the actual size of any given structure, and therefore the only way to update something would be to rewrite the entire file.

Or am I wrong in how binary files work, and to modify the second record, I can just do something like:
1
2
seekp(sizeof(Book) * 1);
fileout << book3;


And that would change book2 to book3?

Thanks.
sizeof(Book) is constant. `std::string' holds a pointer that points to where the characters are allocated.
That said, it would be an error to do fileout.write( (char*)&book1, sizeof(book1) ); because the value of the pointer would be meaningless in another run of the program.

20 records is a really small value, you better just rewrite the whole file. However if that size increases consider using a database
That's what I was guessing, that the strings would mess things up. Thanks for confirming.
Topic archived. No new replies allowed.