+ 2
Performing std::string I-O from-to a Binary File [ANSWERED]
I have a class Passenger which I am to store the data of inside a Binary File. I have used std::string instead of char arrays in the class to store the strings. struct Date { int D; int M; int Y; }; struct Location { string DTime, ATime, FlightNo, Dest, Arrival, Dur, FName; }; class Passenger { public: string FirstName, MidName, SurName, Email, Contact, Gender; string MealPref, Requirements, Doc, DocNo, VisaNo, VisaLoc; Date DOB, Exp, VisaExp, DOD, DOR; bool State; double
6 Antworten
+ 1
hi,
first, the cause for the sigfault is, how string stores it's data internally (dynamic memory management through pointers) which lead you after the read to invalid memory locations. actually this is quite dangerous, because you can corrupt memory of other applications or your is.
second, it seems that you have to write a methode which write each member to your file stream!
but note that that string.size() returns the length of the string excluding the trailing '\0'(it returns the same as strlen [1]) so either you you write +1 or an aditional variable with the length of your string.
note that you can store in a string also all your binary data and access them by string.data() maybe this is any help at some point.
always a good idea is to write also a header like total amount of following blob and version number, were you can distinguish different member over time
[1] http://www.cplusplus.com/reference/cstring/strlen/
+ 2
@Gunther Strauss
Now I get it. Thanks a lot!
+ 1
uh, also take care to write size_t directly in your binary file (example by use string.size()) it's different on x86 and x64, cast it before to a other type with constant length
+ 1
@Gunther Strauss
Thank you very much for providing an answer.
I am unable to understand the part where you have asked me to use string.data().
So, I should write my binary data to a string first and then just write a single string to the file? If yes, how is that done? Using stringstream perhaps? Please describe that as well, if possible.
Secondly, Can you also explain the use of the version number member? I have a lot of other members like TicketNumber that are unique for each passenger object, so I don't think any data will be the same for two objects.
+ 1
easy things first:
I meant binary block (or blob) version.
if you change your class the data change that you save.
but with a version number (not in the class but in your binary data) you can call a specific read function/method.
simply forget about that string.data() thing. I don't think its of any use in your case.
but you could write everything to a stringstream, but it's only help full if you want to collect data of more pessangers, and write them at once....
+ 1
glad I could help :)