-
You can't use sizeof(string) to determine the space needed on the file to store a string. You should use a fixed size space for that - there would be several different possible choices here, but you do need to use some method to define how large your string is.
Also, it is not absolutely necessary to use a fixed size record to be able to random access the file - however, if the records are NOT all the same size, then you would need some other way (such as an array of integer indicating "which record is where in the file").
--
Mats
-
>> The reason I am using binary rather than text is because, as I understand it, that is required for random access.
Your strings must have a fixed size for random access to work. Do you really need random access? If you're not sure or you don't really need it, then don't use binary i/o, use text based i/o with the stream operators << and >>.
If you absolutely need random access, then you must use fixed size strings. For that, I'd stop using the string class and instead use a character array of a fixed size. They are not as easy to use as the string class, but are necessary for fixed record length i/o that you pretty much have to have for random access in the file.
-
OK. Could I just convert between string and char array before/after writing/reading to the file? If I can, how can I convert a char array to a string?
Thanks!
-
Just pass it to a string constructor.
std::string s = mychararray;
-
>> Could I just convert between string and char array before/after writing/reading to the file? If I can, how can I convert a char array to a string?
You could do this only if you forced the strings to be a certain size (or smaller). However, it may make more sense to store character arrays in your struct if you have one and do the conversion when storing the data rather than when writing it and reading it.
To convert a character array to string (after reading) just assign it.
To convert a string to a character array (before writing) use strcpy or strncpy:
Code:
const int MAX_NAME_LEN = 100;
// ensure name is small enough to fit. There are other ways to do this, but this one works.
name.resize(MAX_NAME_LEN-1);
char namebuf[MAX_NAME_LEN];
strcpy(namebuf, name.c_str());