I'm doing a final project for coding class and our program has to be menu driven with file IO in the command prompt. The only problem is saving a vector of structs into a file. I got the part where it saves the User struct (by commenting out the vector), but I don't know how to get it to write and read a vector of structs from a file. We haven't gotten to the part with saving structs to binary files in class yet (we will on Monday). Can anyone help me on how to write/read a vector of structures into/from the people.dat file?
file.write(reinterpret_cast<char *>(&u1), sizeof(u1));
Terribly wrong. You cannot save non-POD types like that. You need to write proper serialization routines yourself.
For saving variable length data there are two main approaches:
1) Sentiel teminated: you write your data one by one and after last one write a sentiel value. It can be '\0' symbol for strings, stucture in which all fields are set to predefined nonsentual values or something else.
2) Counted. You write amount of data and then write n entries of data. Example: pascal string — first byte is a number of characters in string, then n characters.
cool, it reminds the project of my first year of university. Reading your code I cannot understand how people would actually prefer a style of wasting a line for just a parenthesis { } as opposed to K&R. It leaves me astounded.
For the rest I agree with Minipaa, you are trying to store a pointer char* instead of the actual data. As Minipaa said, you need some kind of serialization strategy.
Well the truth is, we have not gotten to this topic in class yet, so I'm just looking ahead in my textbook and trying to do what i can from what the examples show.
Now this approach works until you have fixed size items. In case you want to deal with varying length data (such as strings), minipaa already suggested two strategies: delimit your string with some special character (such as '\0') or prepend them with their size. An example for the second case would be: